Skip to main content
 首页 » 编程设计

python之如果您要求整数但没有得到整数,是否存在异常

2025年05月04日9oomusou

我正在尝试制作一个输入整数的程序,但如果您不输入整数,则将其处理为异常。但是我在互联网上找不到整数的任何异常(exception)情况。

### 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