r/learnpython • u/hispters • 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*4it prints 4444, not 12. Could somebody help me with my syntax? Thanks so much!
6
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."1
u/hispters Feb 16 '13
OP here, I'm a total noobie, I wasn't trying to use "is" for any reason other than I couldn't get "=" to work (I now understand why :P )
3
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
aandbpoint 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 withraw_inputit 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 sayiswould work here. If you were manually assigning toracein the code (like I was in my quick test before posting), it would work, but withraw_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.
1
u/zahlman zahlman Feb 16 '13
In 2.x, you could explicitly
intern()strings, but that's gone now. I guess it was seen as too error-prone and too likely to encourage bad code.2
Feb 16 '13
It's under
sys.intern()in 3.x apparently.2
u/zahlman zahlman Feb 16 '13
Oh! I guess I shouldn't be surprised. They did end up moving a lot of things that people expected to disappear completely (like
reduce).1
u/hispters Feb 16 '13
Thank you too! I got stumped after trying the last post, but after looking at yours I figured out I needed to say "race== "elf" or race=="Elf". So thanks! :)
2
u/Zouden Feb 16 '13
I think every person learning a programming language makes this mistake. It's probably the most common question in this subreddit :)
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
2
u/Deusdies Deusdies Feb 16 '13
What others have said, but I'd like to add one more thing. Instead of doing:
if race == "Elf" or race == "elf":
You ought to do this:
if race.lower() == "elf":
As you may imagine, this will ("temporarily" in this case) lower the case of the race variable. I think this is a better solution because what would happen if your user inputted "ELF"?
Also, you can even consider changing from this:
race = raw_input("Whats your race")
to:
race = raw_input("Whats your race ").lower()
1
u/hispters Feb 16 '13
Thanks! I used race.lower(), but thanks for showing me the shorcut of using .lower() after the input.
11
u/Mecdemort Feb 16 '13
If you're comparing something to multiple things you can use if race in ('elf', 'Elf'). in this case you may also do if race.lower() == 'elf'.
You should only use is and is not if you're comparing something to None.
7
u/Cosmologicon Cosmologicon Feb 16 '13
You should only use
isandis notif you're comparing something toNone.Well, that's pretty good advice for a beginner, and the OP certainly should not be using them in this case, but there are other legitimate uses for
isandis not.
2
u/atypicaloddity Feb 16 '13
Just a guess, but I think it's the if race is "elf" or "Elf" line.
Consider the pseudocode:
if (race == "elf" OR "Elf")
This checks first if race is "elf", and then checks if "Elf"... nothing. "Elf" isn't compared, so it just returns true.
x = 5
if x: print("Five")
returns "Five".
Changing it to if race is "elf" or race is "Elf": should fix it.
1
u/_pH_ pH34r-pH Feb 16 '13
Since it doesnt seem like it's been answered:
num=3
print num*4This is telling it to print the value of num four times. I do python 3, so I dont know if there's a different option in 2.7, but replacing it with
print (num*4) Might fix it. If not,
x = num*4
print xWill definitely work.
1
u/HorrendousRex Feb 16 '13
No, sorry, that's not true - in Python, you can't 'multiply' a function invocation, rather just its result. You can in ruby (sort of) using their '4.times.do{}' block construct, but python doesn't have that feature. (You can do it with loops or with something like
map(range(4), lambda x: foo()).)OP: Can you provide a screenshot or
pythonsession transcript where the two lines at the bottom of your post print '4444'? I'm sorry but it doesn't seem likely - I get 12 every time.On the other hand what DOES seem likely is that instead of having
num=3you might havenum="4", and then"4"*4 == "4444". That would cause this.1
u/JerMenKoO jermenkoo Feb 17 '13
Wrong.
Numwas a number, so it should print 12 unless he didn't changeintclass. (or let it inherit from string)
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
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
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