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

6

u/[deleted] Feb 16 '13 edited Feb 16 '13

You're not using or correctly. "Elf" in your first statement evaluates to True (any non-empty string does), and so that first condition always ends up being true. You need a complete statement on the right of the or: if race is "elf" or race is "Elf":.

Now with that said, you'll probably want to use == instead of is. Due to the immutable nature of strings, is does work here, but you're really checking equality not identity, so the == is better. Edit: See my post below as to why is actually doesn't work in this case.

2

u/Advent667 Feb 16 '13

Random post from not-op, i could not get Is to work in this code, could you? mine just defaults to the else statement.

race=raw_input("Whats your race ")

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

3

u/[deleted] Feb 16 '13 edited Feb 16 '13

After further digging, there's something interesting going on here which I was unaware of:

>>> a = "test"
>>> id(a)
36910184L
>>> b = "test"
>>> id(b)
36910184L
>>> c = raw_input()
test
>>> id(c)
45582816L
>>> 

Notice how a and b point to the same memory address, as I would expect. String are immutable, so Python knows it can save space by not creating identical strings in memory. But with raw_input it doesn't perform the same optimization and creates a new spot in memory even though that particular string is already stored. So I was wrong to say is would work here. If you were manually assigning to race in the code (like I was in my quick test before posting), it would work, but with raw_input() it doesn't.

The more you know.

Either way though, identity isn't really want this code should be checking.

1

u/Advent667 Feb 16 '13

interesting, yeah i understood "==" was the correct response, was just curious how you got "is" to work but nevermind now. Thank you for showing me that.