I'm studying Zed shaw's learn python 3 the hard way book and there's a part in the code i'm trying to improve.
My aim was to have an if statement with the condition that the input the user gives is of int type.
def gold_room():
print("This room is full of gold. How much do you take?")
choice = eval(input("> "))
if type(choice) is int:
how_much = choice
else:
print("Man, learn to type a number.")
if how_much < 50:
print("Nice, you're not greedy, you win!")
exit(0)
else:
print("You greedy bastard!")
gold_room()
It works if the input is indeed an integer but if I type in a string i get the error:
NameError: name 'string' is not defined
I tried to use int() but then if the input is a string I get an error. Is there a way to do this?
Use choice = int(input("> "))
. The int
function will convert the string that the input
function gives you into an integer. But if it can't, it will raise an exception (ValueError), that you may want to try-except.