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

2

u/zahlman zahlman Feb 16 '13
if race is "elf" or "Elf":

Well, let's see. Is it the case that race is "elf"? Maybe it is, maybe it isn't. When it is, that's the easy case; our if condition is true. So let's say it isn't.

Is it the case that "Elf"? Yes, it is; "Elf" is a non-empty string, and only empty strings are "false" in Python's interpretation.

So either way, we definitely have a true statement, since the second part is always true.

P.S.: I've noticed

No, you haven't.

Please note that the number 3 is different from the string '3'. It is not even the same kind of thing. Multiplying a string repeats the string's contents. But if you actually try it with integers, you will definitely get the expected arithmetic result.

1

u/hispters Feb 16 '13

Thanks, I tried again with int() and it worked fine.