Skip to content
Suggested Lab. Exercises · Q2

Q.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.

Odisha ChseTextbookSubjective· 3mImportance★★★★★est
75% · 30/40 Questions
✓ Free question

A user-defined function takes the name and the gender code (M/F) as parameters and prints the name prefixed "Mr" for M or "Ms" for F, with .upper() making the code case-insensitive and an else-branch catching invalid codes.

The idea. This is selection driven by function parameters: the decision data (gender) and the payload (name) both arrive through the parameter list, and a simple if–elif–else ladder picks the output form. Normalising the code with .upper() is the small robustness touch that makes m and M behave alike.

def add_prefix(name, gender):
    # Print the name prefixed Mr/Ms based on the gender code
    if gender.upper() == "M":
        print("Mr", name)
    elif gender.upper() == "F":
        print("Ms", name)
    else:
        print("Invalid gender code:", gender, "- please enter M or F")

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

Sample runs

Enter name: Rahul Verma
Enter gender (M for Male, F for Female): M
Mr Rahul Verma
Enter name: Anita Singh
Enter gender (M for Male, F for Female): f
Ms Anita Singh
Enter name: Kiran Rao
Enter gender (M for Male, F for Female): x
Invalid gender code: x - please enter M or F

How it works

  • The two inputs are read in the main program and passed as arguments; inside the function they are the parameters name and gender.
  • gender.upper() converts the code to capitals before comparing, so lower-case entries (second run) still match.
  • The else branch keeps the program honest on bad input instead of printing a wrong prefix or crashing.
Tip

To build the full string rather than just print it, return it instead: return "Mr " + name. The caller can then store it, write it to a file, or print it — returning is more flexible than printing.

✓Final answer

The function prefixes the name by gender: M → Mr <name>, F → Ms <name> (accepting lower-case codes via .upper()), and reports any other code as invalid.

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.