2

I would like to ask the user to input the gender. if the user's answer is not male or female, I want to loop the question again and again until the user enter male or female

here is what I wrote:

while not (mf):
    gender=input("Next, the gender of the character is (male/female):")
    if gender == ("male") or ("female"):
        mf=True
    else:
        print("Enter the correct gender type.")

if I enter female when asking gender, it would treat as wrong, but both female and male should be correct answer.

Cœur
  • 37,241
  • 25
  • 195
  • 267
KI TO
  • 61
  • 4

3 Answers3

8

You can use while True, which is commonly used:

while True:
    gender = input("Next, the gender of the character is (male/female):")
    if gender in ["male", "female"]:
        break
    print("Enter the correct gender type.")

print(gender)
nicolas
  • 3,120
  • 2
  • 15
  • 17
4

The statment of gender == ("male") or ("female") is always true

change it into: gender in ['male', 'famale']

Explanation:

doing gender == ("male") or ("female"), there is two expressions here, one is gender == ("male") which is the right one, but after it comes the or keyword, which make the next thing a statement too, so the next statement is ('female') which is a truly value, so it will always be true

Reznik
  • 2,663
  • 1
  • 11
  • 31
  • okay, I get it. Thanks a lot for answering, i tried it for a long time. – KI TO Dec 14 '19 at 14:44
  • @KITO no problem :) if you think it's the right answer you can mark it as currect (check nicolas answer too, its not really explaning the error, but its a good practice) – Reznik Dec 14 '19 at 14:44
-1

I will suggest the below code to avoid using a new variable for the sake of storing if the input is correct, which you can directly check using the gender variable you're already using.

gender = "" # initialize the variable
while not (gender in ['male', 'famale']):
  gender = input("Next, the gender of the character is (male/female):")
  if not gender in ['male', 'famale']:
    print("Enter the correct gender type.")
IamAshKS
  • 749
  • 4
  • 14