0

I am trying to compare an input value for error handling but my if statement returns true the first time then false the second time. I am checking if the input value is not equal to "male" or "female".

Method 1:

def init_greeating(self):
        gender = input("Enter your gender\n")
        gender = gender.lower()
        if(gender != "male" or gender != "female"):
            gender = input("I do not know that gender. Try again ")
        return  

Output

Enter your gender 
male
I do not know that gender. Try again
male
How excellent! Are you a CS Major? 

Method 2

def init_greeating(self):
        gender = input("Enter your gender\n")
        gender = gender.lower()  

        if gender != "male":
            gender = input("I do not know that gender. Try again\n")      
        elif gender != "female":
            gender = input("I do not know that gender. Try again \n")
        return

Output

Enter your gender 
    male
    I do not know that gender. Try again
    male
    How excellent! Are you a CS Major? 

I am not sure what I am missing. Any guidance will help.

acebelowzero
  • 107
  • 1
  • 5

2 Answers2

2

In your first method, you have 2 boolean statements in one. The first checks if it's not male, and the second checks if it's not female. If either are true, then it'll say it doesn't understand that gender. So, if you inputted male, then it would say that not male is false, but not female is true, meaning it'll say it doesn't know your gender.

In your second method, the same applies. It'll skip the first if statement because it knows for sure that not male is false, but it'll pass the elif statement because it knows that not female is true, so it'll say it doesn't know your gender.

As such, instead of checking for what the gender ISN'T, check for what it IS, then use an else statement for "I don't understand that gender."

Dharman
  • 30,962
  • 25
  • 85
  • 135
harbar20
  • 33
  • 5
2

The reason your first code doesn't work is because or would still make it get in to the loop even if it's male, because gender != 'male' would give False, but gender != 'female' would give True.

Whereas:

>>> False or True
True
>>> 

So you would need and:

def init_greeating(self):
    gender = input("Enter your gender\n")
    gender = gender.lower()
    if gender != "male" and gender != "female":
        gender = input("I do not know that gender. Try again ")
    return  

It's the same case for example 2. The elif will still run because gender == 'male'.

So try this for the second example:

def init_greeating(self):
    gender = input("Enter your gender\n")
    gender = gender.lower()  

    if gender == "male":
        return      
    elif gender == "female":
        return
    gender = input("I do not know that gender. Try again\n")
U13-Forward
  • 69,221
  • 14
  • 89
  • 114