Input and Output
Reading from the keyboard with input(), writing with print(), and turning text into numbers.
Standard input and standard output
Every program the operating system starts gets three standard channels, called streams, already opened for it. Standard input (stdin) is where the program reads text from — by default the keyboard. Standard output (stdout) is where it writes its normal results — by default the terminal window. A third stream, standard error (stderr), is meant for error messages and warnings, so they stay visible even when the normal output goes elsewhere.
In Python, input() reads from standard input and
print() writes to standard output. The streams are also
available as objects in the sys module:
sys.stdin, sys.stdout and
sys.stderr.
import sys
sys.stdout.write("Written to stdout directly\n")
print("Written by print()")
Written to stdout directly Written by print()
Redirection
Because the program only sees "a stream", the shell can connect it
to something other than the keyboard and screen, without any change
to the code. < feeds a file into standard input,
> sends standard output to a file, and
| connects the output of one program to the input of
the next:
python3 greet.py < names.txt # read input from a file
python3 report.py > report.txt # save output in a file
echo "Ada" | python3 greet.py # pipe another program's output in
Writing output with print()
print() accepts any number of arguments of any type. It
converts each one to text (with str()), writes them
with a space in between, and ends with a new line. With no arguments
it prints just an empty line.
city = "Nairobi"
print("Temperature in", city, "is", 24.5, "degrees")
print(3, True, None)
print()
print("After an empty line")
Temperature in Nairobi is 24.5 degrees 3 True None After an empty line
The sep and end parameters
Two keyword arguments change what print() puts
between and after the values. sep is
the separator (default " "); end is
written at the very end (default "\n", a new line).
Setting end="" lets the next
print() continue on the same line.
print("2026", "09", "30", sep="-")
print("a", "b", "c", sep="")
print("Loading", end="")
print("...", end="")
print(" done")
print("x", "y", sep=", ", end=".\n")
2026-09-30 abc Loading... done x, y.
Printing to standard error
The file parameter chooses the stream. Warnings and
error messages belong on standard error, so that they do not end up
in a file when the output is redirected:
import sys
print("Warning: disk almost full", file=sys.stderr)
Reading input with input()
input(prompt) writes the prompt to standard output,
waits until the user types a line and presses Enter, and
returns that line without the new line at the end. The
program pauses while it waits.
name = input("What is your name? ")
print(f"Hello, {name}!")
What is your name? Ada Hello, Ada!
In the output above, Ada is what the user typed; a
terminal shows it right after the prompt. input() adds
nothing to the prompt, so end it with a space, or the answer will be
glued to it.
input() always returns a string
Whatever the user types — a name, a number, nothing at all —
input() returns a str. An empty line gives
the empty string "". So arithmetic on input fails, or
worse, silently does something else:
age = input("Age: ")
print(type(age))
print(age * 2) # string repetition, not multiplication!
print(age + 1)
Age: 36 <class 'str'> 3636 TypeError: can only concatenate str (not "int") to str
Converting text to numbers
Type conversion (also called
casting) creates a value of one type from a value of another. You do
it explicitly by calling the type: int(),
float(), str(), bool(). The
usual pattern is to wrap input() directly:
age = int(input("Age: "))
height = float(input("Height in meters: "))
print("Next year you will be", age + 1)
print("You are", str(round(height * 100)) + " cm tall")
Age: 36 Height in meters: 1.75 Next year you will be 37 You are 175 cm tall
A few details are worth knowing. int() and
float() ignore spaces around the number and accept a
sign. int() also takes a base as its second argument.
But int() does not accept a decimal point: convert to
float first if you need that.
print(int(" 42 "), int("-7"))
print(float("2.5"), float("1e3"))
print(int("ff", 16), int("101", 2))
print(int(float("3.5")))
42 -7 2.5 1000.0 255 5 3
Python also converts some types implicitly: in
2 + 0.5 the integer is turned into a float
automatically. It never does that between numbers and strings, which
is why the conversion above is always needed.
When the input is not a number
If the text cannot be converted, int() and
float() raise a ValueError, and the
program stops:
quantity = int(input("Quantity: "))
print("Ordered", quantity)
Quantity: twelve ValueError: invalid literal for int() with base 10: 'twelve'
To keep the program running, catch the error with
try and except. The details are on the
page about error handling; the
basic shape is:
text = input("Quantity: ")
try:
quantity = int(text)
print("Ordered", quantity)
except ValueError:
print(f"'{text}' is not a whole number.")
Quantity: twelve 'twelve' is not a whole number.
Several values on one line
input() reads one whole line. To let the user type
several values on it, split the string, then convert each part.
line = input("Width and height: ")
width, height = line.split()
area = int(width) * int(height)
print("Area:", area)
Width and height: 3 4 Area: 12
If there is no more input at all — the input file has ended, or the
user pressed Ctrl+D —
input() raises an EOFError.
Formatting output
Calculations often produce numbers with more digits than you want to
show: 2.95 * 3 is 8.850000000000001.
Format the number when you print it. An f-string with a format
specifier changes only how the value is displayed;
round() actually creates a new, rounded number.
item = input("Item: ")
price = float(input("Price: "))
quantity = int(input("Quantity: "))
total = price * quantity
print(total)
print(f"{quantity} x {item:<10} {total:>8.2f}")
print(f"Total with 21% VAT: {total * 1.21:,.2f}")
Item: Notebook Price: 2.95 Quantity: 3 8.850000000000001 3 x Notebook 8.85 Total with 21% VAT: 10.71
The format specifiers for width, alignment, decimals and thousands separators are explained under f-strings on the Strings page.