Reputation: 19
I am working out of the Learn Python the Hard Way book and I have a very beginner question. I am trying to get it so that the code below does not have to go through such a weird way to check if a number was given, also, I want numbers that don't have 1 or 0 to be valid.
def gold_room():
print("The room is full of gold, how much do you take?")
choice = raw_input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
The idea that I had was to get it to check if choice was an integer, and if so then trigger the code, but I can not figure out how to do this. I am sure the answer is very simple, and I'm sorry for such a basic question. Thank you for your help!
Upvotes: 0
Views: 64
Reputation: 57033
If you are looking only for non-negative integers, than choice.isdigit()
will suffice. It returns True
or False
, depending on whether choice
consists of all digits or not. Complete solution:
def gold_room():
choice = raw_input("The room is full of gold, how much do you take? ")
if choice.isdigit():
return int(choice)
else:
return None
Upvotes: 2
Reputation: 9257
You can use, also, try .. accept
and catch the error.
You can follow this example:
def gold_room():
print("The room is full of gold, how much do you take?")
choice = raw_input("> ")
try:
return int(choice)
except ValueError:
pass
print gold_room()
Output:
if for example the input was 12
>> 12
if the input isn't an integer so the output will be None
:
>> None
Upvotes: 1