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.
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
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
Step 1: Define a user-defined function 'addPrefix' with two parameters - name and gender
Step 2: Inside the function, use if-elif-else to check gender value
Step 3: If gender is 'M' or 'm', print 'Mr.' followed by name
Step 4: If gender is 'F' or 'f', print 'Ms.' followed by name
Step 5: Accept name and gender as input from user
Step 6: Call the function by passing name and gender as arguments