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.
'Insights' 카테고리의 다른 글
BOJ Problem 2675: Analyzing Escape Character with a Debugger (1) | 2024.11.15 |
---|---|
BOJ Problem 10809: Does the find() return only the index? (3) | 2024.11.08 |
BOJ Problem 3052: Is "{}" a set or a dict? (3) | 2024.11.01 |
Committing to GitHub using VS Code: user.name, user.email (3) | 2024.10.25 |