Defining names in python

后端 未结 3 710
借酒劲吻你
借酒劲吻你 2021-01-21 17:38

I am confused on why my program is not working. I am supposed to use nested ifs to ask people their name and title(doctor, female, male) and then print out either Ms. name Mr. n

相关标签:
3条回答
  • 2021-01-21 17:57

    Because you have made some Indentation issues and you don't need to use nested if else try this:

    name = input("Enter your name : ")
    title = input("Enter your title (doctor, female, male) : ")
    
    female = ("Ms."+name)
    doctor = ("Dr."+name)
    male = ("Mr."+name)
    
    if title == "doctor":                                                                                                                                                                                                                                                
        print(doctor)
    elif title == "male":
        print(male)
    else:
        print(female)
    
    0 讨论(0)
  • 2021-01-21 18:09

    The logic for your if statements should be the following:

    1. print Dr + name if title is doctor

    2. print Mr + name if title is male

    3. print Ms + name if title is female

    These three statements are parallel to each other, so there shouldn't be a nested if statement in the first place. I suggest you read up on the if - elif - else statement in python

    if title == "doctor": 
        print(doctor)
    elif title == "male":
        print(male)
    else:
        print(female)
    

    If you want nested if-statements, then you need to change your logic. Here is one example.

    1. if title is not doctor

      a) check if title is male and print male

      b) print female (since if title is not doctor or male, it has to be female. unless you are allowing invalid input)

    2. else print doctor

    if title != "doctor": 
        if title == "male":
            print(male)
        else:
            print(female)
    else:
        print(doctor)
    
    0 讨论(0)
  • 2021-01-21 18:09

    You much more careful:

    name = input("Enter your name : ")
    title = input("Enter your title (doctor, female, male) : ")
    
    female = ("Ms.")
    doctor = ("Dr.")
    male = ("Mr.")
    
    if title == "doctor":                                                                                                                                                                                                                                                
        if title != "male":
            print(doctor)
        else:
            print(male)
    else:
        print(female)
    

    if and else should be in the same line

    0 讨论(0)
提交回复
热议问题