Why it matters
A program that never asks for anything can only do what it was written to do. A program that reads input can solve any problem that has the same shape. Judges for competitive programming and coding interviews give your program its input as a stream of text, and your program must read that text correctly and as fast as the limits require. A wrong read gives a wrong answer even when the algorithm is perfect. A slow read gives a time-limit error on a large test, even when the algorithm is fast.
This lesson covers input(), the simplest way to read in Python, and the layout problems that catch almost everyone at least once. It then shows sys.stdin, which you use when the input is large. Both read from the same source, the standard input, which is the stream the input box in this course feeds, or the keyboard when you run the file in a terminal.
The idea: input is text, and you convert it
Input arrives as text: digits, letters, spaces and line breaks. Python does not guess what the text means. input() reads one line and returns it as a str, without the line break at the end. If you want a number, you convert it yourself with int() or float(), as the type conversion lesson showed.
line = input()
print(repr(line))If you type 42 and press Enter, the output is '42'. The quotes show that the value is text. The number is still text until you convert it:
line = input()
number = int(line)
print(number + 1)If you type 42, the output is 43. The conversion is the step that most beginners miss. The error for skipping it is in the mistakes section.
Reading a prompt and one value
The function input takes an optional prompt. The prompt is printed before the program waits for the user, on the same line.
r = float(input("Radius: "))
area = 3.14 * r * r
print("Area:", area)Type 2 after the prompt and press Enter. The screen shows Radius: 2 and then Area: 12.56. The area is 3.14 * 2 * 2, which is 12.56. The prompt stays on the same line as the cursor, so the user types on the line where the question appeared. There is no need for a separate print for the question.
The programs in this lesson read from the keyboard or from a file, so they are not in the Run box. Type the sample input when the program asks for it, or pipe it in from another command when you test on your own computer.
Reading several values on one line
Many inputs put several values on one line, separated by spaces. The method split cuts the line at the spaces and returns a list of text pieces. The function map applies int to each piece, so the whole line becomes a list of numbers.
a, b = map(int, input().split())
print("Sum:", a + b)Type 4 7 and press Enter. The output is Sum: 11. The line a, b = ... unpacks the list of two numbers into two names. If the line has a different number of values, Python stops with an error, and the message names the problem. The mixed types section below shows this error.
The parentheses around a + b are not needed in Python here, because the sum is computed before it is printed. Compare this with the line print("Sum: " + str(a + b)), where str is needed, because text and a number cannot be joined directly.
The layout trap: a count and its values on one line
The most common input bug in Python is a layout that does not match what the program reads. Judges often send a count and the values on separate lines. Some tests put them on one line. A program that reads a line for the count and then a line for the values fails when the layout changes.
n = int(input())
values = list(map(int, input().split()))
print("Sum:", sum(values[:n]))With the input 3, Enter, then 10 20 30, the output is Sum: 60. With the input 3 10 20 30 on one line, the first int(input()) gets the text "3 10 20 30", and the program stops:
Traceback (most recent call last):
File ".../trap.py", line 1, in <module>
n = int(input())
ValueError: invalid literal for int() with base 10: '3 10 20 30'The message shows the whole line, which is the first thing to check. The line that failed is the one that reads the count. The fix is to read tokens rather than lines, so the layout does not matter. The next section shows how.
Reading all the input at once
The standard input is a stream. sys.stdin.read() returns all of it as one string, and split() with no argument cuts that string at any whitespace, including spaces, tabs and line breaks. The result is a list of tokens in the order they appeared. A token is one piece of text between whitespace.
import sys
data = sys.stdin.read().split()
n = int(data[0])
values = list(map(int, data[1:1 + n]))
print("Sum:", sum(values))Both layouts now give the same answer. With 3, Enter, 10 20 30, the tokens are 3, 10, 20 and 30. With 3 10 20 30 on one line, the tokens are the same. The program never asks where a line ends. The slice data[1:1 + n] takes the next n tokens after the count. The output for both layouts is Sum: 60.
Use this pattern when the problem says the input has a fixed shape. It reads the whole input before the program does anything else, which is fine for judges and for most tests.
Reading until the input ends
Many problems do not give a count. They say "read numbers until the end of the input". Two ways do this in Python. The first reads all the tokens and loops over them, as the previous section did. The second reads one line at a time until input() reports that the input has ended.
import sys
count = 0
total = 0
for token in sys.stdin.read().split():
total += int(token)
count += 1
print("Count:", count)
print("Sum:", total)Type 4 8 15 16 23 42 and then the end of the input. The end of the input is Ctrl+D on Linux and macOS, or Ctrl+Z and Enter on Windows. The output is Count: 6 and Sum: 108. When you test without a keyboard, pipe the text in with printf or echo.
The second way uses input() and the exception EOFError. Python raises this error when input() is called after the end of the input. The try block catches it, and break leaves the loop.
count = 0
total = 0
while True:
try:
line = input()
except EOFError:
break
for token in line.split():
total += int(token)
count += 1
print("Count:", count, "Sum:", total)The output for the same input is Count: 6 Sum: 108. The try and except pair is how Python handles an error you expect. The error happens only at the end of the input, and the except branch turns it into the normal exit from the loop. The exception rules are covered in a later module.
If the input is empty, sys.stdin.read() returns an empty string, the loop never runs, and the output is Count: 0 and Sum: 0. Test this edge case every time. It is one of the first things an interviewer tries.
Reading a count, then that many values
Judges usually give the number of values first, then the values. This pattern reads the count, then the values, and tracks a running answer. The example below finds the largest value. It reads the values from the stream of tokens, so it works whether the values are on one line or several.
import sys
data = sys.stdin.read().split()
n = int(data[0])
values = list(map(int, data[1:1 + n]))
largest = values[0]
for value in values:
if value > largest:
largest = value
print("Largest:", largest)Type 5, Enter, then 3 9 2 9 7. The output is Largest: 9. The variable largest starts at the first value, which is always one of the values, so the loop only needs to compare the rest. The built-in max(values) gives the same answer in one call. The loop is shown here because the same pattern works for any running answer, such as a smallest value or a count of matches.
Some solutions start the maximum at a very small number, for example float("-inf"). That also works, because every real value is larger than negative infinity. Starting at 0 is wrong when every value is negative, and that is a common interview follow-up.
Reading a grid
A two-dimensional grid is a common input shape. The first two numbers give the number of rows and columns. The values follow, row by row. The program below reads the grid and prints the sum of each row.
import sys
data = sys.stdin.read().split()
rows, cols = int(data[0]), int(data[1])
numbers = list(map(int, data[2:]))
grid = [numbers[r * cols:(r + 1) * cols] for r in range(rows)]
for r, row in enumerate(grid):
print(f"Row {r}: {sum(row)}")Type 2 3, Enter, 1 2 3, Enter, then 4 5 6. The output is Row 0: 6 and Row 1: 15. The list comprehension cuts the flat list of numbers into rows of cols values each. The slice numbers[r * cols:(r + 1) * cols] takes row r. The program does not care where the line breaks fall, because it reads tokens.
Two-dimensional lists are the subject of the arrays module. For now, read grid[r][c] as "the value in row r and column c", and notice that the row index comes first.
Checking what the user typed
Users make typing mistakes, and so do test files. A program that calls int on a word crashes with an exception. The safe pattern is to check the text before converting it, or to catch the exception when the conversion fails.
text = input()
if text.isdigit():
print("You entered", int(text))
else:
print("Please enter a whole number.")Type abc, and the output is Please enter a whole number.. Type 42, and the output is You entered 42. The method isdigit is True only when every character is a digit, so it fails for -5 and for 3.5. For those inputs, use try and except:
text = input()
try:
n = int(text)
print("You entered", n)
except ValueError:
print("Please enter a whole number.")Type -5 and the output is You entered -5, because int accepts a minus sign. Type abc and the output is Please enter a whole number. The except ValueError branch runs when int cannot read the text.
When you skip the check, the failure looks like this:
Traceback (most recent call last):
File ".../ask.py", line 1, in <module>
n = int(input())
ValueError: invalid literal for int() with base 10: 'abc'The last line names the error and the text that failed. Read it the same way as the other messages in this course: the error type first, then the text, then the line that made the call.
Fast input with sys.stdin
input() is convenient, but it does some work for each line. For a few thousand lines it is fast enough. For a million lines on a judge, the time can matter. sys.stdin.readline reads one line of text with less overhead, and sys.stdin.buffer.readline reads the raw bytes, which is faster still. Use them when the input is large and the time limit is tight.
import sys
read_line = sys.stdin.buffer.readline
n = int(read_line())
values = map(int, read_line().split())
total = 0
for value in list(values)[:n]:
total += value
print("Sum:", total)Type 3, Enter, then 10 20 30. The output is Sum: 60. The read_line name holds the function, so the program does not look up the attribute each time it reads. read_line() returns bytes, and int and split accept bytes, so no decoding step is needed for numbers.
The price of speed is responsibility. With line reads, you must handle the layout yourself. If the numbers can be spread over several lines, you need a loop that reads a new line whenever the current one runs out. The token version from the earlier section handles any layout without that loop. Use input() when you want the simplest code, sys.stdin.read().split() when the layout is free and the input fits in memory, and sys.stdin.buffer.readline when the time limit demands it.
Mixed types on one line
Real input often mixes types on one line: a name, an age and a height, for example. Read the tokens in the order they appear, and convert each one to the type it needs.
name, age, height = input().split()
age = int(age)
height = float(height)
print(f"{name} is {age} years old and {height} m tall")Type Ravi 25 5.9 and the output is Ravi is 25 years old and 5.9 m tall. The line name, age, height = input().split() gives three text values. The conversions come next.
Notice that split() cuts at every space. If the name were Ravi Kumar, the line would have four tokens, and the unpacking would fail. The error is ValueError: too many values to unpack (expected 3, got 4). When a name can contain spaces, read the whole line as text and take the number from the end, or put the name on its own line and read it with input().
Reading from a file
The keyboard is one source of input, and judges often use files. The same functions read a file when you open it. On a terminal, you can also redirect a file into the program without changing the code. If the program is main.py and the data is in data.txt, the command python3 main.py < data.txt feeds the file in as standard input, and the program sees it exactly as it would see typed text.
with open("data.txt") as f:
data = f.read().split()
print(len(data), "tokens")The with statement opens the file and closes it when the block ends, so you do not need a separate close call. Redirection is the fastest way to test a program against a large input that you saved earlier. Keep the file in the folder with your code, and check the output against the expected answer.
What happens with the stream
input() and sys.stdin read from one stream, and Python keeps a buffer, which is a block of text read ahead of the program. When you read a line, Python may already have read the next lines into the buffer. This is why sys.stdin.read() seems to wait after you type a number: it keeps reading until the input ends, so press Ctrl+D (Ctrl+Z and Enter on Windows) to finish.
Mixing input() with sys.stdin.buffer in the same program can lose data, because one reader takes the block that the other one expected. Choose one way to read in a program, and read the whole input through it.
A checklist for input problems
When an input problem gives you trouble, go through this list in order.
- Write down the exact input format from the problem. Is the count given first? Are the values on one line or many? Are there blank lines?
- Write down the type of every token. Convert each one with
int,floator leave it as text. - Decide whether the layout matters. If it does not, read tokens with
split(). If it does, read lines and say so in a comment. - Store every value you need in a name at the time you read it. A stream does not give tokens back.
- Test the empty input and the smallest valid input, such as a count of 1, before the large cases.
- Test with one layout and with another layout that the problem allows, such as all the values on one line.
- Check the largest sum or product the input can produce. Python
intdoes not overflow, so the sum is exact, but a sum of a billion values can still be slow or large in memory.
A program that passes this checklist is ready for a judge. It is also a good script to say out loud in an interview, because it shows that you think about the input before you type any code.
Common mistakes
These are the mistakes beginners make with input. Each one has a message you can recognise or a wrong output you can check.
- Forgetting to convert.
input() + 1givesTypeError: can only concatenate str (not "int") to str. Writeint(input()) + 1. - Converting a line that holds several values.
int("3 10 20 30")givesValueError: invalid literal for int() with base 10: '3 10 20 30'. Split the line first, or read tokens withsys.stdin.read().split(). - Reading a name that has spaces with split.
name, age = input().split()fails onRavi Kumar 25, because there are three tokens. Read the name on its own line. - Typing letters for a number.
int("abc")givesValueError. Check withisdigitor usetryandexcept. - Reading past the end.
input()givesEOFError: EOF when reading a linewhen the input has run out. Loop withsys.stdin.read()or catchEOFError. - Keeping the line break.
sys.stdin.readline()returns the text with\nat the end.intandsplitignore it, but a comparison such astext == "42"fails. Use.strip()orinput(). - Mixing readers. Calling
input()andsys.stdin.buffer.readlinein one program can lose lines. Pick one reader.
Practice
Work each exercise yourself before you open the solution. Type the sample input when the program asks for it.
- Read two decimal numbers and print their average as a
float. Test with3.5and4.5. - Read a first name with
input()and printHello,followed by the name. Test withRavi, then withRavi Kumarand explain the output. - Read a full name with spaces using
input()and print its length. Test withRavi Kumar. - Read an integer count, then a line of text, then print the text in capital letters. Make sure the text is not empty.
- Read numbers until the input ends and print how many of them are even.
- Read a count
nand thennnumbers, and print the smallest of them. - Read a number of test cases
t. For each one, read a single integer and print its double. Each answer goes on its own line. - Read two integers, but print an error message if the second one is zero instead of dividing by it. Print a message if either value is not a whole number.
- Read a grid of
rrows andccolumns and print the sum of the whole grid. Test with values near 10 to the power 9. - Read one line and print the number of words in it, counting words as tokens separated by whitespace. Handle two spaces in a row.
- Explain in two sentences why Python does not need a
longtype for a sum of a hundred thousand numbers near one billion each, and what limit remains. - Write a program that reads a name on one line and an age on the next. Convert the age with
int. Test with a non-number age and print a message instead of crashing.
Each exercise has an answer below a "Show the answer" line. Try each one first, then read the answer.
- Read the two values, convert them, and divide the sum by 2.
Show the answer
a = float(input())
b = float(input())
print((a + b) / 2)For 3.5 and 4.5 the output is 4.0.
- The name is the whole line, so
input()reads it in one step.
Show the answer
name = input()
print("Hello, " + name)With Ravi Kumar the output is Hello, Ravi Kumar, because input() reads the whole line. The space is not a problem here, because no token splitting happens.
- Use
lenon the whole line.
Show the answer
full = input()
print(len(full))For Ravi Kumar the output is 10, counting the space.
- The first line is the count, and the second line is the text. Reading the count with
input()and then the text with anotherinput()works, because eachinput()reads one whole line.
Show the answer
n = int(input())
text = input()
print(text.upper())Check that text is not empty if the problem requires it, for example with if text:.
- Count the even numbers among the tokens.
Show the answer
import sys
count = 0
for token in sys.stdin.read().split():
if int(token) % 2 == 0:
count += 1
print(count)- Read the count, then the values, and take the minimum.
Show the answer
import sys
data = sys.stdin.read().split()
n = int(data[0])
values = list(map(int, data[1:1 + n]))
print(min(values))- Read the count of test cases, then one integer per case, and print each double on its own line.
Show the answer
t = int(input())
for _ in range(t):
value = int(input())
print(2 * value)- Check each value before using it, and check the divisor before dividing.
Show the answer
try:
a = int(input())
b = int(input())
except ValueError:
print("Both inputs must be whole numbers.")
else:
if b == 0:
print("Cannot divide by zero.")
else:
print(a / b)- Read the size, then the values, and add them up. Python
intdoes not overflow, so a plain sum is exact.
Show the answer
import sys
data = sys.stdin.read().split()
rows, cols = int(data[0]), int(data[1])
total = sum(map(int, data[2:2 + rows * cols]))
print(total)- Split the line with no argument, which ignores extra spaces, and count the pieces.
Show the answer
line = input()
print(len(line.split()))For an empty line, split() returns an empty list, so the answer is 0.
-
Each value is about one billion, and the running sum can reach about 10 to the power 14, which Python
intholds exactly, so no special type is needed. The limit that remains is memory and time: a list of a hundred thousand values takes space, and a judge limits how long the program may run. -
Use
input()for both lines, and convert the age inside atryblock.
Show the answer
name = input()
age_text = input()
try:
age = int(age_text)
print(f"{name} is {age} years old.")
except ValueError:
print("Age must be a whole number.")What you now know
input()reads one line and returns text. Convert it withintorfloatbefore you do arithmetic.split()cuts text at whitespace.map(int, ...)converts each piece to a number.sys.stdin.read().split()reads every token in order, so the layout of the line breaks does not matter.- A count and its values can share a line in one test and sit on separate lines in another. Read tokens to handle both.
- Read until the input ends with a loop over the tokens, or with
input()andexcept EOFError. - Check text with
isdigitfor simple cases, or convert insidetryand catchValueError. - Use
sys.stdin.buffer.readlinewhen the input is large and the time limit is tight.