What I expect from making this code is, I input some numbers, then when I input strings the output is 'Not Valid', but when I press enter without putting some value to input, the output is the sum of numbers that we input before. But when I run it on VSCode, whenever I press enter, the result always 'Not Valid', and can't get out of the loop.
For example, I input: 1 2 3 a z
then the output I expect is: Not valid Not valid 6
I don't know what is wrong, I just learned python 2 months ago.
sum = 0
while True:
try:
sum += int(input())
except ValueError:
print('Not Valid')
except EOFError:
print(sum)
break
When you don't input anything,
input()
will return the empty string. Converting it to an integer is invalid, so you get theValueError
:To trigger
EOFError
, send the EOF signal with Ctrl + D:Here the
^D
represents me pressing Ctrl + D on the keyboard (not literally typing "^D").