print()
The built-in print()
function lets you display text or other data to the standard output or another output stream. By default, the output is displayed on the screen, but it can be redirected to a file or other output stream:
>>> print("Hello, World!")
Hello, World!
print()
Signature
print(*objects, sep=" ", end="\n", file=None, flush=False)
Arguments
Argument | Description | Default Value |
---|---|---|
*objects |
An arbitrary number of Python objects to be displayed | end |
sep |
The string used to separate the objects | " " (space) |
end |
The string appended after the last object | "\n" (newline) |
file |
The file-like object where the output is sent | sys.stdout |
flush |
A Boolean value that specifies whether to forcibly flush the output buffer | False |
Return Value
- The
print()
function returnsNone
. - It performs an output operation as a side effect, displaying or writing the input objects.
print()
Examples
With a single string argument:
>>> print("Hello, Real Python!")
Hello, Real Python!
With multiple arguments and a custom separator:
>>> print("Python", "is", "fun", sep=" - ")
Python - is - fun
Redirecting output to a file rather than to sys.stdout
:
>>> with open("output.txt", "w") as file:
... print("Hello, file!", file=file)
print()
Common Use Cases
The most common use cases for the print()
function include:
- Displaying messages or results to the user
- Debugging by showing variable values or program states
- Logging information to a file
- Creating simple text-based user interfaces (TUI)
print()
Real-World Example
Create a simple progress bar for a command-line interface using the print()
function. This progress bar will visually indicate the completion percentage of a task:
def progress(percent=0, width=30):
end = "" if percent < 100 else "\n"
left = width * percent // 100
right = width - left
print(
"\r[",
"#" * left,
" " * right,
"]",
f" {percent:.0f}%",
sep="",
end=end,
flush=True,
)
# Usage
from time import sleep
for percent in range(101):
sleep(0.1)
progress(percent)
# Output: [########### ] 38%
This code will display a progress bar that updates in place as the task progresses. The flush=True
ensures that each update is immediately shown on the screen.
Related Resources
Tutorial
Your Guide to the Python print() Function
In this step-by-step tutorial, you'll learn about the print() function in Python and discover some of its lesser-known features. Avoid common mistakes, take your "hello world" to the next level, and know when to use a better alternative.
For additional information on related topics, take a look at the following resources: