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

9

u/Advent667 Feb 16 '13

ok i am not sure how the "is" operator works but i fear that is your problem.

you ask why you can not use "=" well that is because it is the assignment operator, you need the comparison operator "==" so your if statement should read like

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

for both elf and orc and then it worked fine for me. I make the assignment/comparison operator mixup all the time :) I hope this helps

4

u/hispters Feb 16 '13

It does indeed! This clears up so much. I'm not sure why I used "is", but thanks for clearing up the confusion with "=="!

1

u/noeras Feb 16 '13

You can use 'is' in python you can also do something like this so you are not duplicating code:

if race.lower() is "elf": ...

4

u/epsy Feb 16 '13

No, just don't use is. is compares the location of the objects in memory, it does not test them for equality.

2

u/Advent667 Feb 16 '13

Honestly, i was testing this code with the assignment operator and was very stumped why it would not worked...like i said, i make the mistake all the time haha.

2

u/Advent667 Feb 16 '13

and for a final replay, i found this on the "is" operator http://stackoverflow.com/questions/2438667/what-is-the-semantics-of-is-operator-in-python it seems the is operator compares memory addresses. the reason the top if statement always went off was because of the part after the "or", you just compare the memory location of string "Elf" to nothing which means its always true

2

u/[deleted] Feb 16 '13

It's actually not doing any comparing or memory-address stuff with "Elf" in the OP's code. It's simply the fact that non-empty strings always evaluate to True.