无法捕获EOFError

问题描述

通过编写此代码,我期望输入一些数字,然后在输入字符串时输出为“无效”,但是当我按Enter键而不输入任何值时,输出就是数字的总和。我们之前输入。但是当我在VSCode上运行它时,每当我按Enter键时,结果始终为“无效”,并且无法退出循环。

例如,我输入:1 2 3 a z,然后我期望的输出是:Not valid Not valid 6

我不知道出什么问题了,两个月前我才学习python。

sum = 0
while True:
    try:
        sum += int(input())
    except ValueError:
        print('Not Valid')
    except EOFError:
        print(sum)
        break

解决方法

不输入任何内容时,input()将返回空字符串。将其转换为整数是无效的,因此您得到了ValueError

>>> input() # next line is empty because I just pressed Enter

'' # `input()` returned the empty string
>>> int('') # can't convert it to an integer
Traceback (most recent call last):
  File "<stdin>",line 1,in <module>
ValueError: invalid literal for int() with base 10: ''

要触发EOFError,请通过 Ctrl + D 发送EOF信号:

>>> input()
^DTraceback (most recent call last):
  File "<stdin>",in <module>
EOFError

这里的^D代表我按下键盘上的 Ctrl + D 不是实际键入“ ^ D”)。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...