I am currently trying to learn Python 2.7 via Learn Python The Hard Way, but have a question about Study Drill 5 of Exercise 35.
The code I'm looking at is:
choice = raw_input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
else:
dead("Man, learn to type a number.")
The study drill asks if there is a better way than checking if the number contains zero or one, and to look at how int()
works for clues.
I obviously want to be able to accept any number given by the user while dismissing strings, and I understand that int()
converts what was given in raw_input()
into a number.
So, I tried a couple of ways of amending the if statement which threw up fatal errors when typing a string, but struggled to find anything suitable. I tried variations of the following code, and now understand why they don't work:
choice = int(raw_input("> "))
if choice > 0:
After searching SO I discovered this answer which gives two ways to solve the problem, however try...except
and .isdigit()
aren't something mentioned in the book at this point.
Is there any other ways to achieve taking user input, converting it to an integer if necessary, and returning an error if not that is appropriate for this stage of the book?