1

Ill make this short.

My code is:

if player_gender != "male" or "Male" or "female" or "Female":

    print("Try again")
else:
    print("Great!")

Im not sure why but it will constantly output the "Try again" message regardless whether or not I type the correct words: (Male, male, Female, or female).

While putting in the correct gender type, I was expecting it to pass over the "Try again" message since I used the "!=" operator, and then jump straight to the "Great!" message. But it always says "Try again"

VICE VERSA

Ive also tried

if player_gender == "male" or "Male" or "female" or "Female":
    print("Great!")
else:
    print("Try Again")

Here I'd always get "Great!" and never "Try again" even when I purposely choose a word that does not correspond to a gender.

Also I know the past I've heard of a ways to make my if statement shorter instead of:

if player_gender == "male" or "Male" or "female" or "Female":

Is there some sort of phrase or symbol that will include both lowercase and uppercase spellings? I'd rather learn that way for future projects.

And Yes I am a newbie Lol I get how easy this question is and im sure ill be face palming once I realize my error. BUT ANY OTHER HELP, ADVISE, OR CRITICISM IS GREATLY APPRECIATED!! =)

Dcode
  • 75
  • 1
  • 5
  • 2
    This is a very common pitfall! You can't use `or` here in Python like you can in English. See [How to check if a variable is equal to one string or another string?](https://stackoverflow.com/questions/12774279/how-to-check-if-a-variable-is-equal-to-one-string-or-another-string) for what you can do instead – that other guy Nov 23 '19 at 04:07
  • I hope my answer helps. Please let me know if you have more specific questions. – FatihAkici Nov 23 '19 at 04:34

1 Answers1

0

If you check multiple conditions in one if statement like:

if player_gender != "male" or "Male" or "female" or "Female":
    Do something

How Python evaluates that is:

if player_gender != "male": Do something
or if "Male": Do something
or if "female": Do something

Now what does if "Male" mean? This is checking whether "Male" is some non-empty string, which is True. "Blabla" is evaluated to True, because it is not Falsey. It is not an empty string or a 0 integer or a False boolean or an empty list/tuple/dict.

Proper way of checking that if is:

if player_gender != "male" or player_gender != "Male" or player_gender != "female" or player_gender != "Female":
    Do something

Better yet:

if player_gender not in ["male", "Male", "female", "Female"]:
    Do something
FatihAkici
  • 4,679
  • 2
  • 31
  • 48