Python Module 2 – Values, variables, numbers and strings
Input and output: print(), input() and stdin
Control what print() writes with sep, end, file and flush, read and check what users type with input(), and read whole inputs from stdin for coding judges.
What you will learn
- Explain where standard input, standard output and standard error go
- Use sep, end, file and flush to control what print() writes
- Read user input with input() and convert it safely
- Read many lines from standard input for judge-style problems
- Choose a conversion that never runs code that a user typed
Before you start
What you’ll learn · Before you start
What you will learn
- Explain where standard input, standard output and standard error go
- Use sep, end, file and flush to control what print() writes
- Read user input with input() and convert it safely
- Read many lines from standard input for judge-style problems
- Choose a conversion that never runs code that a user typed
Before you start
On this page
A coding judge runs your program on an input such as 5, 10 20 and 30 40 50 on three lines, and compares what
the program prints with the expected answer, 6 numbers, total 155. Reading text and writing text is all that
happens there, and every program talks to the outside world the same way, through three
standard streams: The three text channels every program starts with: standard input to read from, standard output for its results and standard error for messages. In Python they are sys.stdin, sys.stdout and sys.stderr..
Below, you control what print() writes and where it goes, read and check what a person types with input(), read
a whole input the way judges give it, and see why a program must never run text that someone typed.
Every program reads one stream and writes two
A program reads from standard input, writes its results to standard output, and writes error messages to
standard error. In a terminal all three are connected to the terminal itself, but the shell can connect them to
files or to other programs, a redirection: Connecting a program's standard input or output to a file or to another program instead of the terminal, as the shell does in python3 solve.py < input.txt > out.txt., and that is how online judges and coding tests
feed a program its data and collect its answer. The diagram follows the three streams from where the text comes in to
where each one goes, with the shell’s <, >, 2> and |:
The three standard streams of a program
Text description of the diagram
The diagram shows, from top to bottom, where a program's text comes from and where it goes.
- At the top is standard input (stdin): the keyboard, or a file when the program is started with < file, or the output of another program after a | pipe.
- An arrow labelled input(), sys.stdin leads from it down to your program: input() reads one line of it, sys.stdin reads it as a file.
- From your program, one arrow labelled print() leads to standard output (stdout), which is the screen, or a file after > file.
- Another arrow, labelled file=sys.stderr, leads to standard error (stderr): print(…, file=sys.stderr) writes there. It is the screen too, unless the program is started with 2> file, so error messages stay visible when the normal output goes to a file.
Each stream is a file object of the sys module: sys.stdin, sys.stdout and sys.stderr. input() and print()
use them for you, and later sections use them directly where that is clearer.
Checkpoint
Check: The three standard streams
print() writes its values with sep between them and end after
print() writes its arguments to standard output, turning each into text with str(). Four keyword arguments
change what it writes and where:
import sys
# By default print() puts a space between values and a line break at the end.
print("tea", "coffee", "juice")
print("tea", "coffee", "juice", sep=", ")
print("tea", "coffee", "juice", sep="")
# end replaces the line break, so the next print() carries on the same line;
# flush=True writes "Saving" out at once instead of keeping it in the buffer.
print("Saving", end="", flush=True)
print("...", end=" ")
print("done")
# Values of any type are written with str(); print() on its own writes an empty line.
print(42, 2.5, True, None, [1, 2])
print()
# file=sys.stderr sends a message to standard error instead of standard output.
print("warning: the price list is empty", file=sys.stderr) Output
tea coffee juice tea, coffee, juice teacoffeejuice Saving... done 42 2.5 True None [1, 2]
Printed as an error (standard error)
warning: the price list is empty
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 print_options.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
sepgoes between the values (a space unless you say otherwise), andsep=""glues them together.endis written after the last value (a line break unless you say otherwise).end=""orend=" "lets the nextprint()carry on the same line.file=sys.stderrsends the text to standard error. The output above shows it under its own label: error messages stay visible on the screen even when a user saves the normal output in a file with> results.txt, and they do not end up mixed with the results.flush=Truemakes Python write the text at once, as the program does for “Saving”. Output is normally collected in a output buffer: Memory where written text waits before it is sent on: a line at a time when standard output is a terminal, in larger blocks for a file or a pipe. print(..., flush=True) sends it at once. first: a line at a time in a terminal, and in larger pieces when it goes to a file or a pipe. So a progress message printed withend=""may appear late unless you addflush=True, as inprint("Working…", end="", flush=True), and lines on standard output and standard error can come out in a different order from the one the program wrote them in.
The four calls below sum up what sep and end add around the values, with every line break named:
| Call | What it writes |
|---|---|
print("tea", "coffee") |
tea coffee and a line break |
print("tea", "coffee", sep="") |
teacoffee and a line break |
print("Saving", end="") |
Saving, and no line break |
print() |
a line break on its own |
Commas in a print() call are often all you need to join values: print("Total:", 5) works where
print("Total: " + 5) raises TypeError, because + cannot add a number to a string. An f-string gives you full
control over the layout. Press Edit, add sep="-" to the first print() of the program and run it: that line
becomes tea-coffee-juice.
Checkpoint
Check: What print() writes
input() returns one line, always as a string
input() waits for one line of input and returns it as a string, without the line break at the end. With an
argument, it first writes that prompt to standard output, without a line break. Whatever the user types is text,
even 29, so a number must be converted, and the conversion must be checked, because people mistype:
name = input("Your name: ").strip()
# Ask again until the answer is a whole number.
while True:
text = input("Your age: ")
try:
age = int(text)
break
except ValueError:
print(f"{text!r} is not a whole number, try again.")
print(f"Hello, {name}! Next year you will be {age + 1}.") Input (standard input)
Kavya twenty 29
Output
Your name: Your age: 'twenty' is not a whole number, try again. Your age: Hello, Kavya! Next year you will be 30.
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 ask_age.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
.strip()removes spaces the user typed by accident.int()ignores spaces and a line break around the digits by itself, so" 29"is read as 29.int(text)raisesValueErrorfor text that is not a whole number, such as"twenty". Thetryblock catches it, explains the problem and asks again; thewhile Trueloop (the control-flow lessons cover loops) ends withbreakonce a number has been read.- The output looks run together because the answers came from the input shown above it, not from a keyboard:
input()writes each prompt and then reads a line without printing it. In a terminal, the user’s typing is shown by the terminal itself, so each answer appears after its prompt.
Step through the same run one message at a time, from each call of input() to the string it hands back:
The drawing shows the whole scene; its 8 steps are listed below.
Every step as text
- A call with a prompt. The program calls input() with the prompt "Your name". Nothing else in the program runs until input() returns.
- The prompt goes out. input() writes the prompt to standard output without a line break, so a person sees it and types right after it.
- One line comes back. The first line of the input is Kavya and a line break. input() reads that line, line break and all.
- A string is returned. input() drops the line break and returns the rest as a string. The program's .strip() then takes away any spaces typed by accident.
- The age, as text. The next call writes "Your age" in the same way and reads the second line, the word twenty. input() hands it back as a string, as it does every line.
- int() refuses it. int() raises ValueError for 'twenty'. The except block prints that the answer is not a whole number, and the while loop calls input() again.
- A number at last. The third line is a space and 29. input() returns ' 29', still a string, and int() ignores the space around the digits and gives the number 29.
- The greeting. break ends the loop, and the program prints its greeting with age + 1, which is 30. Three calls to input() read three lines; a fourth would raise EOFError.
Note
The code runners of this site cannot pause a program to wait for your typing, so they give it all of its input
before it starts. The Run button on this page uses the input shown above the output, and the Python Online
Compiler has an Input box where you type every line before you press Run. In both, input() reads those lines in
order, one per call.
When the input runs out
When there is nothing left to read, input() raises EOFError (EOF is short for
end of file (EOF): The point where a stream has nothing left to read. input() raises EOFError there, sys.stdin.readline() returns an empty string, and a for loop over sys.stdin simply stops.):
first = input()
print("Read:", first)
# There is no second line, so input() raises EOFError.
second = input()
print("Read:", second) Input (standard input)
first line
Output (exit status 1)
Read: first line
Printed as an error (standard error)
Traceback (most recent call last):
File "end_of_input.py", line 5, in <module>
second = input()
EOFError: EOF when reading a line
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 end_of_input.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
When you type the input in a terminal, you end it by pressing Ctrl-D (macOS and Linux) or Ctrl-Z followed by Enter
(Windows). A program that reads until the end of its input should not count on a fixed number of input() calls;
the next section shows the usual ways.
Checkpoint
Check: Reading a line with input()
A judge’s input is read whole or line by line
Online judges and coding tests give a program all of its input on standard input and compare what it prints with the expected answer. Two patterns cover most problems. The first reads everything at once:
import sys
# Read everything at once and split it into words, whatever the line breaks.
words = sys.stdin.read().split()
total = 0
for word in words:
total += int(word)
print(len(words), "numbers, total", total) Input (standard input)
5 10 20 30 40 50
Output
6 numbers, total 155
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 sum_all.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
sys.stdin.read() returns the whole input as one string, and split() cuts it into words on spaces and line breaks
alike, so the program does not care how the numbers are spread over lines. Follow that input through the program,
stage by stage:
The drawing shows the whole scene; its 5 steps are listed below.
Every step as text
- The judge's input. The input is three lines, 5, then 10 20, then 30 40 50 with extra spaces. The program does not know how many numbers each line holds.
- Read it all. sys.stdin.read() returns the whole input in one call, a string of 21 characters with the line breaks and spaces still in it.
- Split on any whitespace. split() with no argument cuts at every run of spaces and line breaks and drops the empty pieces, so how the lines were laid out no longer matters.
- Convert and add. The loop turns each word into a number with int() and adds it to total, which ends at 155.
- The answer. The program prints 6 numbers, total 155, and it would print the same however the judge spread the numbers over lines.
The second pattern goes line by line:
import sys
# A for loop over sys.stdin reads one line at a time and stops at the end of the input.
for line in sys.stdin:
print(repr(line), "->", line.rstrip("\n").upper())
# readline() returns "" once the input has run out, instead of raising EOFError.
print(repr(sys.stdin.readline())) Input (standard input)
tea chai latte
Output
'tea\n' -> TEA 'chai latte\n' -> CHAI LATTE ''
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 line_by_line.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
A for loop over sys.stdin gets one line per turn, each with its "\n" still on the end (which is what repr()
makes visible; only the last line can lack it, when the input does not end with a line break), and stops when the
input ends, without an EOFError. sys.stdin.readline() reads a single line and returns an empty string once there
is nothing left. On your own computer, you can feed a program a whole file exactly as a judge does:
python3 solve.py < input.txt (py solve.py < input.txt in the Windows Command Prompt). PowerShell has no < for
input, so there you pipe the file in instead: Get-Content input.txt | py solve.py.
Key idea
Read a judge’s input whole with sys.stdin.read().split() when only the values matter, and with a for loop over
sys.stdin when the lines do; neither counts on knowing how many lines will come.
Checkpoint
Check: Reading a judge's input
Never eval() what a user types
eval(text) runs text as a Python expression. You may see eval(input()) used to read a number or a list, but
it runs anything the user types, and an expression can import modules, read files and delete them. Convert
numbers with int() or float(), which accept numbers and nothing else.
| Call | What it accepts | Runs code? |
|---|---|---|
int(text), float(text) |
a number written as text | No |
ast.literal_eval(text) |
Python literals: numbers, strings, lists, dictionaries and the like | No |
eval(text) |
any expression at all | Yes, whatever it is given |
For text that holds a Python literal, such as a list or a dictionary, ast.literal_eval() reads the value and
refuses anything that would run code:
import ast
# literal_eval() reads Python literals (numbers, strings, lists, dictionaries …) and nothing else.
print(ast.literal_eval("[3, 1, 2]"))
print(ast.literal_eval("{'tea': 20, 'coffee': 30}"))
# Anything that would run code is refused, where eval() would have run it.
try:
ast.literal_eval("__import__('os').getcwd()")
except ValueError as error:
print("refused:", type(error).__name__) Output
[3, 1, 2]
{'tea': 20, 'coffee': 30}
refused: ValueError
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 literal_eval.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Security
Treat everything a program reads, from a user, a file or the network, as untrusted. Convert it with a function that
accepts only the format you expect, limit its size, and handle the error when it does not fit. Even
ast.literal_eval(), which runs no code, is not recommended by its documentation for untrusted data: a small
crafted input can use up memory or crash the interpreter. Keep it for text you trust, such as a value your own
program wrote, and use a data format such as JSON (a later lesson) for data from outside.
Checkpoint
Check: Converting without running code
Practise: read marks from judge-style input
The exercise reads the layout many judge problems use: a count on the first line and the values on the next. Write the
function so that it works on a list of lines and on sys.stdin alike, and refuses input that does not fit the layout.
Sample tests run in the page, and the first hint sits under the prompt:
Exercise · Easy · Python
Read marks from judge-style input
Online judges and coding tests give a program its data on standard input in a fixed layout. In this one, the first line holds n, the number of students, and the second line holds their n marks, separated by spaces:
3
70 80 95
Write read_marks(lines), which takes the lines of such an input and returns the average mark, rounded with round(average, 2). For the input above it returns 81.67.
linescan be a list of strings such as["3", "70 80 95"], or an open file such assys.stdinor anio.StringIO, whose lines still end with"\n". A program would callprint(read_marks(sys.stdin)).- The numbers may have extra spaces around them, and lines after the second are ignored.
- Raise
ValueErrorwhen the second line is missing, whennis less than 1, when the second line does not hold exactlynmarks, or when a mark is not a whole number, such as80.5oreighty.
The sample tests import your function from marks.py.
Starter code · marks.py
def read_marks(lines):
"""Return the average of the n marks on the second line, rounded to two decimals."""
# Replace this line with your code.
return 0.0 The sample tests · test_marks.py
import io
from marks import read_marks
def raises_value_error(lines):
"""True when read_marks(lines) raises ValueError."""
try:
read_marks(lines)
except ValueError:
return True
return False
def test_lists():
"""averages the marks of a list of lines"""
assert read_marks(["3", "70 80 95"]) == 81.67
assert read_marks(["4", "10 20 30 40"]) == 25.0
assert read_marks(["1", "100"]) == 100.0
def test_files():
"""reads lines that end with a line break, as a file gives them"""
assert read_marks(io.StringIO("3\n70 80 95\n")) == 81.67
assert read_marks(io.StringIO(" 2 \n 50 61 \n")) == 55.5
def test_extra_lines():
"""ignores the lines after the second"""
assert read_marks(["2", "40 60", "not a mark"]) == 50.0
def test_wrong_count():
"""raises ValueError when the number of marks is not n"""
assert raises_value_error(["3", "70 80"])
assert raises_value_error(["2", "70 80 90"])
def test_missing_line():
"""raises ValueError when there is no second line"""
assert raises_value_error(["3"])
assert raises_value_error([])
def test_bad_values():
"""raises ValueError for n below 1 and for marks that are not whole numbers"""
assert raises_value_error(["0", ""])
assert raises_value_error(["-1", "5"])
assert raises_value_error(["2", "70 eighty"])
assert raises_value_error(["2", "70 80.5"]) A hint
list(lines) turns a list, a file or an io.StringIO into a list of its lines, so you can check its length and take rows[0] and rows[1]. int() ignores spaces and the "\n" around a number, split() with no argument does the same for the marks, and int("eighty") raises the ValueError you need without any extra check.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.
Last, the questions on this lesson come one at a time, starting from what you have missed or not tried yet, with each answer explained as soon as you check it:
Practice that adapts to you
Practise this lesson
14 questions about 5 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Fresher · What does input() return, and how do you read a number with it safely?
input() reads one line from standard input and returns it as a string without its line break; with an argument, it
first writes that prompt to standard output. The result is always text, even when the person typed 42, so a number
has to be converted. Call int(text) or float(text) inside try and catch ValueError, which they raise for
anything that is not a number, such as "forty" or "4 2", and a loop can then ask again. int() ignores spaces and
a line break around the digits, so .strip() is optional there. Never use eval(input()) to get a number, because it
runs whatever the user types. When the input runs out, input() raises EOFError, so a program that reads an unknown
number of lines should loop over sys.stdin instead.
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher to mid
A solution reads a million numbers, one per line, with int(input()) in a loop. It passes the small tests but runs out of time on the large one. Explain where the time goes, rewrite the reading, and say how you would measure the gain without the judge.
-
Fresher to mid
A calculator program reads each line with eval(input()), so that users can type 2 + 3 * 4. Explain why that is unsafe, and replace it with code that accepts arithmetic on numbers and nothing else.
Key takeaways
- A program reads standard input and writes standard output and standard error, and the shell can connect each of them to a file or to another program.
print()writes to standard output;sepgoes between values,endafter them,file=sys.stderrsends error messages to standard error andflush=Truewrites at once.input()returns a string without the line break; convert it withint()orfloat()insidetryand handleValueError.- At the end of the input,
input()raisesEOFError, while a loop oversys.stdinsimply stops. - For judge-style input,
sys.stdin.read().split()reads every value at once, and aforloop oversys.stdinreads line by line. - Never pass user input to
eval(). Convert numbers withint()orfloat(), and keepast.literal_eval()for literals from a source you trust.
Terms in this lesson
- end of file (EOF)
- The point where a stream has nothing left to read. input() raises EOFError there, sys.stdin.readline() returns an empty string, and a for loop over sys.stdin simply stops.
- output buffer
- Memory where written text waits before it is sent on: a line at a time when standard output is a terminal, in larger blocks for a file or a pipe. print(..., flush=True) sends it at once.
- redirection
- Connecting a program's standard input or output to a file or to another program instead of the terminal, as the shell does in python3 solve.py < input.txt > out.txt.
- standard streams
- The three text channels every program starts with: standard input to read from, standard output for its results and standard error for messages. In Python they are sys.stdin, sys.stdout and sys.stderr.
References
- print() (Built-in Functions) (Python Software Foundation)
- input() (Built-in Functions) (Python Software Foundation)
- sys.stdin, sys.stdout and sys.stderr (sys, System-specific parameters and functions) (Python Software Foundation)
- ast.literal_eval() (ast, Abstract Syntax Trees) (Python Software Foundation)
- eval() (Built-in Functions) (Python Software Foundation)
- The Python Tutorial: Input and Output (Python Software Foundation)
- The Python Tutorial: Invoking the Interpreter (the end-of-file character) (Python Software Foundation)
- about_Redirection (PowerShell) (Microsoft)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress