Sub topic 1
Writing output with print()
print() is the function most Python programs use to show results. Its defaults cover simple cases. Its three keyword arguments, sep, end and file, control nearly everything else you need from it. This chapter covers how print() turns values into text, how to control the layout, and the mistakes that most often trip people up.
Prerequisites
This chapter assumes you can:
- Run a Python script or use the interactive prompt.
- Work with variables and the built-in types
str,intandfloat. - Read basic
ifandwhilecode. Later chapters use these, though this one barely does.
You do not need to know about files, streams or exceptions yet. The file argument is introduced briefly here and covered fully later.
What print() actually does
The signature of print() is:
print(*objects, sep=" ", end="\n", file=None, flush=False)For each call, Python does four things in order:
- It converts every positional argument to text with
str(). - It joins those pieces with
sep. - It appends
end. - It writes the result to
file. WhenfileisNone, the target issys.stdout, which is normally your terminal.
print() always returns None. It is called for its side effect of writing text, not for a value.
Printing several values
You can pass any number of arguments. By default print() puts one space between them and a newline after the last one.
name = "Ada"
age = 36
print("Name:", name, "Age:", age)
print()
print("done")This prints Name: Ada Age: 36, then a blank line, then done. A call with no arguments writes only the end string, so print() produces an empty line.
Values do not have to be strings. Each one is converted with str(), so numbers, booleans, None and lists all work:
print(1, 2.5, True, None, [1, 2])The output is 1 2.5 True None [1, 2].
Commas versus concatenation
Beginners often combine text with +. That works only when both sides are strings:
count = 5
# print("Count: " + count) # TypeError: can only concatenate str (not "int") to str
print("Count:", count) # Count: 5
print("Count: " + str(count)) # Count: 5Commas are shorter and convert the values for you. Later chapters show f-strings, which are better still when you need precise layout.
Controlling the separator with sep
sep sets the text placed between arguments. It must be a string, or None (which means the default space).
print("a", "b", "c", sep="-")
print("2026", "11", "26", sep="/")
print("a", "b", "c", sep="")
print("line one", "line two", sep="\n")The four calls print a-b-c, 2026/11/26, abc, and two lines. An empty sep glues the values together. A newline sep puts each value on its own line.
sep has no effect when you pass a single argument, because there is nothing to separate.
Unpacking a list into print()
The * operator expands an iterable into separate arguments. Combined with sep, it prints a list without brackets:
items = ["apples", "pears", "plums"]
print(*items)
print(*items, sep=", ")
print(*items, sep="\n")Compare that with print(items), which shows the list's brackets and quotes: ['apples', 'pears', 'plums']. Unpacking prints the contents. Printing the list prints its text form.
Controlling the ending with end
end is the text written after the last value. Its default is "\n". Replacing it lets the next print() continue on the same line.
print("Loading", end="...")
print("done")This prints Loading...done on one line, because the first call did not emit a newline.
A common use is printing a row of values inside a loop:
for n in range(1, 6):
print(n, end=" ")
print()The loop prints 1 2 3 4 5 and the final bare print() ends the line. Without that last call, your shell prompt would appear on the same line as the numbers.
You can also set end="" to write nothing at all after the text. This is useful for prompts and progress displays.
Output that does not appear: buffering
When you suppress the newline, text may not show up right away. Python buffers output, and a terminal usually flushes its buffer only at a newline. A long-running loop that prints with end="" can look frozen.
Pass flush=True to force the text out immediately:
import time
for step in range(3):
print(".", end="", flush=True)
time.sleep(1)
print(" finished")The dots appear one per second, followed by finished. Use flush=True for progress indicators, or when another program reads your output as it is produced. Do not add it to every call, because flushing on each write slows down programs that print a lot.
Sending output elsewhere with file
The file argument accepts any object with a write() method. The two common targets are open files and the standard streams.
import sys
print("Result: 42")
print("Warning: input file was empty", file=sys.stderr)
with open("log.txt", "w", encoding="utf-8") as f:
print("first entry", file=f)
print("second entry", file=f)The first call writes to standard output. The second writes a diagnostic to standard error, which a shell can redirect separately. The last two write to a file, and print() adds the newline for you, which f.write() does not. A later chapter explains the streams and file modes in detail.
Common errors and surprises
| Symptom | Cause | Fix |
|---|---|---|
| `SyntaxError: Missing parentheses in call to 'print'` | Python 2 style `print "hi"` | Write `print("hi")` |
| Nothing printed, no error | Wrote `print` without parentheses, which only names the function | Add `()` |
| `TypeError` on `"a" + 5` | `+` does not convert numbers | Use commas, `str()`, or an f-string |
| `TypeError: sep must be None or a string` | Passed a number as `sep` | Pass `sep=str(value)` or a string literal |
| Prompt glued to the output | Used `end=""` and never wrote a newline | Finish with a plain `print()` |
| Output appears late | Buffered output with no newline | Add `flush=True` |
| `None` shown in output | Printed the result of a function that does not return a value | Print the value, not the call to `print()` |
The last row comes from print() returning None:
result = print("hello")
print(result)This prints hello and then None. A function that calls print() instead of using return gives the caller nothing to work with. This is a frequent design mistake in early programs. Functions that compute should return values, and the calling code should print them.
Summary of the main arguments
| Argument | Default | Purpose |
|---|---|---|
| `*objects` | none | Values to print, each converted with `str()` |
| `sep` | `" "` | Text placed between values |
| `end` | `"\n"` | Text written after the last value |
| `file` | `sys.stdout` | Object that receives the text |
| `flush` | `False` | Push buffered text out immediately |
Exercise
What does this code print, and why? print("x", "y", sep="") print("z", end="!") print("w")
Show answer
It prints "xy" on the first line, then "z!w" on the second line. The first call uses an empty separator, so x and y join. The second call replaces the newline with "!", so the third call continues on the same line.
Exercise
Write a loop that prints the numbers 1 to 5 on a single line separated by commas with no trailing comma, using one print() call and no loop. What is it?
Show answer
print(*range(1, 6), sep=",") prints 1,2,3,4,5. The star unpacks the range into five arguments, and sep=",", places commas only between values.