Reputation: 5
I'm a beginner who's learning to program in Python and I've ran into this problem. I tried searching for an answer, but I didn't really know what to search for.
Why does my function keep executing 'else', even when I enter a number lower than 150 when asked? It should, instead, run a second function called 'wish_second()', but for some reason it ignores it.
Originally my plan was to get the first function to activate 'else' only when writing a large number, but now it seems to keep on doing that with small numbers and even when writing something like 'asd', when instead it should keep on asking for a valid number.
def wish_first():
print "You decide that you will first wish for gold coins. "
print "How many coins will you wish for? "
while True:
next = raw_input("> ")
try:
how_much = int(next)
except ValueError:
print "Learn to write a number!"
if next < 150:
print "You fill your pockets and think of a second wish. "
wish_second()
else:
dead("A bunch of coins fall on your head and you die.")
def wish_second():
print "You can't decide what you want to wish for. "
print "You're debating wheter to get home or wish for a unicorn. "
Upvotes: 0
Views: 105
Reputation: 206
It doesn't keep asking for a number after you enter an invalid string like 'asd', because there is nothing in the except
block to make it skip the rest of the code and go back to the start of the while True
loop. So, it correctly enters the code in except
, printing out the error message, but then just goes along to the next line which is the comparison.
One way to solve that would be to add the rest of the code inside the try
block, so that it is only executed if the input was a number. For example (note, I have also changed the comparison, as mentioned in the other answers):
def wish_first():
print "You decide that you will first wish for gold coins. "
print "How many coins will you wish for? "
while True:
next = raw_input("> ")
try:
how_much = int(next)
if how_much < 150:
print "You fill your pockets and think of a second wish. "
wish_second()
else:
dead("A bunch of coins fall on your head and you die.")
except ValueError:
print "Learn to write a number!"
Upvotes: 0
Reputation: 50600
You are converting to an int, but never using that variable
how_much = int(next)
But your comparison is against a string - if next < 150:
Change your comparison to use how_much
. You can also do this: next = int(raw_input("> "))
Upvotes: 2
Reputation: 117946
You need to convert to the input value to an int
next = int(raw_input("> "))
Otherwise you are comparing a string
to an int
here
if next < 150:
As pointed out by @davidism, you may also use your variable how_much
since you converted it to an int
already
how_much = int(next)
So you could say
if how_much < 150:
Upvotes: 0