Sub topic 1
Writing output with print()
Prerequisites
This chapter assumes you can run a Python script and know variables, expressions, and the built-in types str, int, and float. You do not need any other background. Later chapters cover input, formatting, and files.
What print() does
print() is a built-in function that converts its arguments to text and writes them to standard output, which is usually your terminal. It accepts any number of arguments and returns None.
print("Hello", 42, 3.5, True)This prints Hello 42 3.5 True. Each argument is converted with str(), and print() puts a space between the values. It then ends the line with a newline character.
Controlling separators and line endings
Two keyword arguments change this behavior:
sepsets the text placed between values. The default is a single space.endsets the text written after the last value. The default is a newline.
print("a", "b", "c", sep="-")
print("Loading", end="...")
print("done")The first call prints a-b-c. The second call writes Loading... and no newline, so the third call continues on the same line. The output is:
a-b-c
Loading...doneSetting sep="" joins values with nothing between them. Setting end="" is a common way to build one line from several calls.
The file argument
print() also takes a file argument that names where the text goes. The default is sys.stdout. Any object with a write() method works, such as an open file or sys.stderr. Later chapters cover both in detail.
import sys
print("Result: 42")
print("Warning: input file was empty", file=sys.stderr)The first line is normal output. The second is a diagnostic message. A shell can redirect the two separately.
Common errors
- Forgetting that
endremoves the newline. If a later line prints nothing visible, check whether an earlier call usedend="". - Passing a list of values.
print(["a", "b"])prints the list with brackets and quotes. To print the items separated by spaces, unpack the list withprint(*items). - Expecting a return value.
x = print("hi")setsxtoNone. Useprint()to show values, not to produce them. - Output that appears late. When output is redirected to a file or pipe, Python may buffer it. Pass
flush=Trueto write immediately.
items = ["red", "green", "blue"]
print(items)
print(*items)
print(*items, sep=", ")This prints the following:
['red', 'green', 'blue']
red green blue
red, green, blueExercises
Exercise
What does the following code print? print("x", "y", sep="") print("z", end="!") print("w")
Show answer
It prints "xy" on the first line. The second and third calls share a line, so the second line is "z!w". The sep="" argument removes the space between x and y, and end="!" replaces the newline after z.
Exercise
You have names = ["Ada", "Grace", "Linus"]. Write one print() call that prints Ada, Grace, Linus on a single line, separated by a comma and a space.
Show answer
print(*names, sep=", ")