Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my while loop is stuck asking the same question even after the correct input was made?

I am learning Python and I have some confusion with while loops. Where am I going wrong?

The goal is to confirm that the client input is between 2 parameters, male or female. If not, I want to loop back to the question until either male or female has been typed into the gender variable.

gender = input("Gender: ")

while True:
    if gender != "male" and gender != "female":
        print(input("Must choose between male and female. "))
    else:
        print("Thank You!")
        break

I was expecting for it to ask “Must choose between male and female.” and after the correct input for it to move on to the next question.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Currently, the code is stuck in displaying “Must choose between male and female.” Even after the correct input was made.

>Solution :

You aren’t re-assigning the value of gender in the failure case. print(input("Must choose between male and female. ")) should be changed to gender = input("Must choose between male and female. ")

gender = input("Gender: ")

while True:
    if gender.lower() != "male" and gender.lower() != "female":
        gender = input("Must choose between male and female. ")
    else:
        print("Thank You!")
        break

Note: I’ve added .lower() in the if clauses to make them case-insensitive.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading