Andrew Andrew - 1 month ago 7
Python Question

Python If/Else Only Returning In Order, Not By Logic

RESOLVED

When an integer containing "0" or "4" is entered, this if-statement only returns the first in the statement.

For example, in the code below, if I enter "60", it will execute:

print "Nice, you're not greedy - you win!" exit(0)

NOT

dead("You greedy bastard!")

as I expected with how_much >= 50.

Have tried a bunch of changes, but can't seem to get to execute as intended. Anyone know what's going on here?

def gold_room():
print "This room is full of gold. How much do you take?"
number_type = False

while True:

choice = raw_input("> ")

how_much = int(choice)

if "0" in choice or "4" in choice and how_much < 50:
print "Nice, you're not greedy - you win!"
exit(0)
elif "0" in choice or "4" in choice and how_much >= 50:
dead("You greedy bastard!")
else:
print "Man, learn to type a number. Put a 0 or a 4 in your number."

Answer

You have an order-of-operations issue. The and operator binds more tightly than the or operator, so when you write:

  if "0" in choice or "4" in choice and how_much < 50:

You are actually getting:

  if ("0" in choice) or ("4" in choice and how_much < 50):

And hopefully, with those parentheses, it's obvious why entering 60 triggers the "Nice, you're not greedy - you win!" message (because it matches the "0" in choice coindition, and since that condition is true, the entire or statement is true).

Add parentheses to get what you want:

  if ("0" in choice or "4" in choice) and how_much < 50:

See this article for details.