How to check for an integer in Python 3.2?

2020-04-20 11:36发布

问题:

I'm trying to write a program where the user inputs a two-digit integer and the output is the second digit printed the amount of times indicated by the first digit. Here is what I have so far:

number = input('Type two-digit integer \n')
a = int(number)//10
b = int(number)%10
if len(number) != 2:
    print(number, 'is not a two-digit integer')
else:
    print(a*str(b))

When I test this out it does what I intend it to do as long as someone types in numbers. If someone were to type in, say, 6r, an error message would pop up saying:

a = int(number)//10

ValueError: invalid literal for int() with base 10: '6r'

So I would assume that something would need to be put in the second line of the code to test if the input is actually an integer, how would I do that? Would I be better off rewriting it in a different way? Please keep in mind that I'm taking an intro course to Python and this is a question on a practice midterm I am taking, so in the case that I would have to answer something like this on the real midterm I can't use a lot of complicated processes.

This is something I tried that works if someone types something that isn't an integer, but for some reason that I don't know it gives the same message for non-integers to integers and doesn't function as I intend it to:

number = input('Type two-digit integer \n')
if (isinstance(number, int)) == False:
    print(number, 'is not a two-digit integer')
elif len(number) != 2:
    print(number, 'is not a two-digit integer')
else:
    a = int(number)//10
    b = int(number)%10
    print(a*str(b))

Help would be greatly appreciated!

回答1:

The best option here is to catch the exception. Something has gone wrong, and that's exactly what exceptions are designed to handle:

try:
    ...
except ValueError:
    print("You need to enter an integer!")
    ...

Python has the mantra of it's better to ask for forgiveness than permission, so don't check if it works beforehand, try it, then handle the problem if it doesn't work.

This makes for more reliable code (the check might accidentally disallow good input, or let through bad input), and makes code read better (you deal with the normal case first, then handle problems, rather than having to check for problems, then process).



回答2:

This is a perfect time for try and except:

try:
   val = int(number)
except ValueError:
   print("That's not a number...")


回答3:

Maybe the simplest thing would be to do number.isdigit(). isdigit will return true if all the characters in the string are digits, which would mean it's a positive integer. So you could do something like:

if not number.isdigit():
    print "You didn't enter an integer!"

Note that using try/except as other answers suggest will allow negative integers, which probably don't make sense for your use case (you can't print a string -2 times).

The thing is that you don't really want "a two-digit integer", you want a string consisting of two digits, which you are going to use as two separate numbers.



回答4:

I'd go for something like:

number = re.match(r'(\d)(\d)', input('Typo two digit number:\n'))
if number is not None:
    print(int(number.group(1)) * number.group(2))
else:
    pass # something wasn't right...