Question 9 of 17intermediate🔧 ApplyLong Answer4 marks

Write a program that uses a user defined function that accepts name and gender (as M for Male, F for Female) and prefixes Mr/Ms on the basis of the gender.

Correct Answer

python

Program to prefix Mr/Ms based on gender

Using user defined function

def addPrefix(name, gender): # Function accepts name and gender as parameters # Checks gender and prefixes accordingly if gender == 'M' or gender == 'm': print("Mr.", name) elif gender == 'F' or gender == 'f': print("Ms.", name) else: print("Invalid gender entered")

Accept input from user

name = input("Enter your name: ") gender = input("Enter gender (M for Male, F for Female): ")

Call the user defined function

addPrefix(name, gender)

Output:

Enter your name: Rahul Enter gender (M for Male, F for Female): M Mr. Rahul

Enter your name: Priya Enter gender (M for Male, F for Female): F Ms. Priya

Exercise: SUGGESTED LAB. EXERCISES | Q: 2 | (Page 30)
For More Understanding

Explanation

This question tests the student's understanding of user-defined functions with string parameters. The function 'addPrefix' accepts two parameters - name (string) and gender (character). Inside the function, conditional statements check if gender is 'M' or 'F' and accordingly prefix 'Mr.' or 'Ms.' to the name. The program demonstrates passing string values as arguments to a function, similar to Program 7-8 in the textbook which shows concatenation of first name and last name. The function uses if-elif-else structure to handle different gender inputs and also includes error handling for invalid gender entries.

Solution Steps

  1. Step 1: Define a user-defined function 'addPrefix' with two parameters - name and gender

  2. Step 2: Inside the function, use if-elif-else to check gender value

  3. Step 3: If gender is 'M' or 'm', print 'Mr.' followed by name

  4. Step 4: If gender is 'F' or 'f', print 'Ms.' followed by name

  5. Step 5: Accept name and gender as input from user

  6. Step 6: Call the function by passing name and gender as arguments