0
while True:
    try:
        n = int(input())
        print(n)
    except EOFError:
        break

I change the code above bit, to make it faster. like down below

import sys
while True:
    try:
        n = int(sys.stdin.readline())
        print(n)
    except EOFError:
        break

but I realized that sys.stdin.readline() doesn't make EOFError after I ran it. than input() is the only way to run the loop that I wrote? or is there any way faster than input

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • stdin may be a file or it may be something else like a terminal. If it is a terminal, it won't EOF. – Ben Feb 05 '22 at 20:01
  • Related, maybe even a duplicate: [What is the perfect counterpart in Python for "while not EOF"](/q/15599639/4518341) – wjandrea Feb 05 '22 at 20:07
  • that loop was kind a chuck for checking the number that i enter it. so i just want to shorten the running time – DanielLee06 Feb 05 '22 at 20:24

2 Answers2

1

input returns an empty line as '', and signals the end of the input with an EOFError.

readline returns an empty line as '\n' and signals the end of the input with ''.

In other words, input raises an exception because it alway strips the trailing end-of-line character and needs some way to distinguish between an empty line and no line.

For your code, you need to check the return value of sys.stdin.readline before you attempt to parse it as an int.

import sys


while (line := sys.stdin.readline()):
    n = int(line)

If readline returns an empty string, the loop exits.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

sys.stdin is a file object, so you could simply loop over it:

for line in sys.stdin:
    n = int(line)
    print(n)
wjandrea
  • 28,235
  • 9
  • 60
  • 81