0

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
ppwater
  • 2,315
  • 4
  • 15
  • 29
Shidqi
  • 1
  • 2

1 Answers1

0

When you don't input anything, input() will return the empty string. Converting it to an integer is invalid, so you get the 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: ''

To trigger EOFError, send the EOF signal with Ctrl + D:

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

Here the ^D represents me pressing Ctrl + D on the keyboard (not literally typing "^D").

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • Ctrl + D maybe not worked for me, but I accidentally press Ctrl + Z and it's worked LOL – Shidqi Oct 21 '20 at 11:49
  • @Shidqi, yes, Ctrl+Z is [the Windows way of sending EOF](https://stackoverflow.com/questions/16136400/how-to-send-eof-via-windows-terminal), and Ctrl+D is the UNIX way. – ForceBru Oct 21 '20 at 17:08