sys.stdin.readline() returns an empty string!
import sys
while True:
try:
userInput = sys.stdin.readline().strip()
print(userInput)
except:
break
EOFError(End of File) means the end of the file, or the end of input. The input() function raises an EOFError at the end of the file, but sys.stdin.readline() returns an empty str, so it does not raise an EOFError. This can lead to incorrect handling due to output overflow.
You can simplify the above code like this:
while True:
try:
print(input())
except:
break
Using sys.stdin.readlines() is also a good approach!
import sys
userInput = sys.stdin.readlines()
for i in userInput:
print(i.strip())
Using sys.stdin.readlines() instead of input() can reduce the time taken. However, both sys.stdin.readline() and sys.stdin.readlines() include a newline character(\n) at the end, so it’s essential to use strip() to remove the newline character.

The difference between sys.stdin.readline() and sys.stdin.readlines() is whether you read one line of input or read all input at once and store each line as an element in a list. In the case of sys.stdin.readlines(), when the user presses Enter, that line is read and added to the list, but it waits until it receives a signal indicating the end of input, so you need to press Ctrl + Z to end the program input.
'Inactive Board' 카테고리의 다른 글
[Python] Call by Value, Call by Reference? (1) | 2024.12.02 |
---|---|
[Python] 백준 11718번: EOFError가 발생하지 않는다고? (0) | 2024.11.23 |
[Python] 연결리스트: 노드가 주소를 가리킨다고? (1) | 2024.11.12 |
[Python] Linked List: What is the Node include? (4) | 2024.11.11 |
[Python] 백준 10809번: find()는 인덱스만 반환하는가? (0) | 2024.11.09 |