简体   繁体   中英

How to fix non integer error, when testing for non-integers entered by input

Trying to finish a small school assignment program, need to finish it by testing for non-int and showing error, and ask for int answers. (Very basic and yet i'm still struggling)

int(input"...")) needs "base 10" and doesn't allow error for non-integer inputs

num1 = input("Please input your first integer: ")
num2 = input("Please input your second integer: ")
#if type(num1) == int and type(num2) == int:

if isinstance(num1,int) and isinstance(num2,int):
    pass
else:
    print("You must enter a number (i.e. 0,1,2...)")
num3 = (num1 * num2)
print("The product of those numbers is: ")
print((str(num3) + ' ') * num3)
if input('Do you want to go again? (y/n) ') == 'n':
    exit

Line 14, num3 = (num1 * num2) can't multiply 'str'

input returns a string by default.

Add these to your code after the first two lines:

print(type(num1), type(num2))
print(isinstance(num1, int), isinstance(num1, str))

To see the problem.

You can try alternatively:

if num1.isdigit() and num2.isdigit():
  pass

instead of isinstance()

Remember that when you perform the arithmetic operations later on you will need to convert these to integers from strings

I think you can convert the input variables to "int" type if it is int number, and catch the exception.

try:
   num1 = int(num1)
except ValueError,e:
   print(e)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM