我正试图制作一个输入整数的程序,但如果不输入整数,请处理一个异常。然而,我在互联网上找不到任何整数的例外。
### TECH SUPPORT ###
while True:
try:
i = int(input('Enter an INTEGER: '))
except [INT EXCEPTION HERE]:
print("You must enter an INTEGER, not any other format of data")
-如果你要求输入一个整数而没有得到一个整数,有人知道例外吗?
您可以随时在解释器中尝试,看看会出现哪个错误:
>>> int('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
既然您知道它是ValueError
,只需更改您的代码:
while True:
try:
i = int(input('Enter an INTEGER: '))
except ValueError:
print("You must enter an INTEGER, not any other format of data")
else:
break # to exit the while loop
是,使用ValueError
关于python的更多信息,请尝试除。浏览内置异常列表,这将对您有所帮助。
此外,当一个内置exception
像这样被抛出时-
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
你可以看到
ValueError: invalid literal for int() with base 10: 'a'
所以python引发了ValueError
,这是您需要使用的异常。
您可以使用"ValueError"异常
while True:
try:
i = int(input('Enter an INTEGER: '))
except ValueError:
print("You must enter an INTEGER, not any other format of data")