isinstance(next, (float, int))
will do the trick simply if next
is already converted from a string. It isn't in this case. As such you would have to use re
to do the conversion if you want to avoid using try..except
.
I would recommend using the try..except
block that you had before instead of a if..else
block, but putting more of the code inside, as shown below.
def gold_room():
while True:
print "This room is full of gold. What percent of it do you take?"
try:
how_much = float(raw_input("> "))
if how_much <= 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
except ValueError:
print "Man, learn to type a number."
This will try to cast it as a float and if it fails will raise a ValueError
that will be caught. To learn more, see the Python Tutorial on it.