Reading Input and Writing Output Like a Judge
18 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A judge feeds your program text and compares what it prints, character by character. Reading and printing correctly is half of the marks, and fast reading often decides large tests.
input() reads one line
Standard input is the stream of text a program reads from. A judge fills it with the test data instead of a keyboard. Both input() and sys.stdin read from it.
A judge gives your program text on standard input. The first line often holds a count, and the next line holds the values. Read each line with input() and convert it.
n = int(input())prices = list(map(int, input().split()))print(sum(prices))Example 1 · Fake input to test locally
import io, sys
sys.stdin = io.StringIO("3\n10 20 30\n")
n = int(input())prices = list(map(int, input().split()))print(n, sum(prices))3 60
What this code does
- Replacing
sys.stdinwithio.StringIOlets you test input code without a judge. - Delete the lines that fake the input before you submit, so the program reads the real input.
input() returns one line as text. split() cuts it at spaces, and map(int, ...) turns each piece into a number.
sys.stdin for big inputs
Token is one piece of input text separated from the next by spaces or line breaks. split() with no argument turns the whole input into a list of tokens.
With 100,000 lines, calling input() each time is slow. Read the whole input once and split it into tokens, then walk through the list.
import sys
data = sys.stdin.read().split()n = int(data[0])prices = list(map(int, data[1:1 + n]))print(sum(prices))Example 2 · Read all tokens at once
import io, sys
sys.stdin = io.StringIO("5\n3 1 4\n1 5\n")
data = sys.stdin.read().split()n = int(data[0])values = list(map(int, data[1:1 + n]))print(values, max(values))[3, 1, 4, 1, 5] 5
What this code does
- The values may be spread over several lines, and read().split() does not care about line breaks.
- This is the safest way to read when the layout of the lines is not guaranteed.
sys.stdin.read() returns all the text at once. The index 1 + n stops the slice after the n prices.
Several test cases and unknown length
Many problems start with the number of test cases. Others give no count, and you read until the input ends. Both patterns are short with sys.stdin.
import sys
cases = int(sys.stdin.readline())for _ in range(cases): sys.stdin.readline() row = list(map(int, sys.stdin.readline().split())) print(max(row))
for line in sys.stdin: print(line.strip())Example 3 · Several test cases
import io, sys
sys.stdin = io.StringIO("2\n3\n4 9 2\n2\n7 1\n")
t = int(sys.stdin.readline())for case in range(1, t + 1): n = int(sys.stdin.readline()) row = list(map(int, sys.stdin.readline().split())) print(f"Case {case}: {max(row)}")Case 1: 9 Case 2: 7
What this code does
- The first line is the number of cases. Each case has a size line and a values line.
- The output format
Case 1: 9comes from the statement, so copy it exactly.
Example 4 · Read until the input ends
import io, sys
sys.stdin = io.StringIO("laptop 2\nmouse 5\nlaptop 4\n")
totals = {}for line in sys.stdin: name, quantity = line.split() totals[name] = totals.get(name, 0) + int(quantity)print(totals){'laptop': 6, 'mouse': 5}What this code does
- The loop stops by itself when the input has no more lines.
line.split()gives two tokens that unpack into a name and a quantity.
readline() reads one line. Looping over sys.stdin gives lines until the end of the input, with no count needed.
Print once and match the format exactly
Judges compare your output text with the expected text. Build the answers in a list, join them, and print once. Match spaces, line breaks and decimal places exactly.
results = [n * n for n in range(1, 6)]print("\n".join(map(str, results)))print(*results)print(f"{2 / 3:.2f}")Example 5 · Output formats
row = [3, 14, 7]print(*row)print(*row, sep=", ")print(*row, sep="\n")print(f"{sum(row) / len(row):.2f}")print("YES" if sum(row) > 20 else "NO")3 14 7 3, 14, 7 3 14 7 8.00 YES
What this code does
sepchanges the text between items, and a separator of a line break prints one item per line.- Print words such as YES and NO exactly as the statement writes them, including capital letters.
print(*results) separates the items by one space. The format .2f always shows two decimal places, so 0.6666 prints as 0.67.
Next step
Check your understanding
10 quick questions