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