r/learnpython • • Feb 16 '13

What's wrong with my if statement?

Hi everybody, I recently learned a bit of Python from code academy, so I decided to try some on my own. Every time I try to use this if statement, it always comes back as the elf response, even if I put in "orc" or "human".

race=raw_input("Whats your race ")

if race is "elf" or "Elf":
    print "Hello, noble elf!"
elif race is "orc" or "Orc":
    print "You do not belong here... leave this place"
else:
    print "I don't recognize you."

No matter what I put it, it replies with "Hello, noble elf!".

Any help? Am I even using the same version of CodeAcademy? (Also why do I use "is" not "=" in the if statement now?) Thanks everybody!

P.S.: I've noticed if I say:

num=3
print num*4

it prints 4444, not 12. Could somebody help me with my syntax? Thanks so much!

11 Upvotes

30 comments sorted by

View all comments

1

u/FourFingeredMartian Feb 16 '13 edited Feb 16 '13

You should remember that race is being set to True, basically in this assignment. If t were blank it would be evaluated as False.

Your if statement, once the assignment happens to race (being non-blank) is being 'shortcut' evaluated.

If you wanted to do a proper assignment check,

if ("elf" or "Elf") == race:

if race.lower() == 'elf':

To me this comes off as very explicit & leaves no room for second guessing. Even in the case above, you can replace '==' with 'is' and get the same result.

2

u/epsy Feb 16 '13

"elf" or "Elf" will always evaluate to "elf"

1

u/FourFingeredMartian Feb 16 '13 edited Feb 16 '13

Frack, you're right, lol, for the same reason I told OP to be wary of -- short circuit evaluation.

It would appear the best fix to resolve this issue is to run the response from raw input from race into the .lower() function & evaluate that way.

Edit: Grammar