Is There A Way Other Than 'try...except' And '.isdigit()' To Check User Input In Python 2?
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('>
Solution 1:
You can write your own is_digit function
def my_digit(input):
digits = ['0','1','2','3','4','5','6','7','8','9']
for i in list(input):
if not i in digits:
return False
return True
Solution 2:
So, firstly read what jonrsharpe linked to in the comments and accept that try
-except
is the best way of doing this.
Then consider what it means to be an integer:
- Everything must be a digit (no decimal point, too)
So that's what you check for. You want everything to be a digit.
Thus, for a represents_integer(string)
function:
for every letter in the string:
check that it is one of "0", "1", "2", ..., "9"
if it is not, this is not a number, so return false
if we are here, everything was satisfied, so return true
Note that the check that is is one of
might require another loop, although there are faster ways.
Finally, consider ""
, which won't work in this method (or GregS').
Solution 3:
Since you already learned sets, you can test that every character is a digit by something like
choice = choice.strip()
for d in choice:
if d not in "0123456789":
# harass user for their idiocy
how_much = int (choice)
Post a Comment for "Is There A Way Other Than 'try...except' And '.isdigit()' To Check User Input In Python 2?"