Skip to content Skip to sidebar Skip to footer

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

defmy_digit(input):
  digits = ['0','1','2','3','4','5','6','7','8','9']
  for i inlist(input):
    ifnot i in digits:
       returnFalsereturnTrue

Solution 2:

So, firstly read what jonrsharpe linked to in the commentsand 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, thisis not a number, so returnfalseif we are here, everything was satisfied, so returntrue

Note that the check that is is one ofmight 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?"