Skip to content

Python Print Statement

Printing in Python is more than just putting words on the screen; it’s a fundamental aspect of communicating with your program’s users and developers alike. In this comprehensive guide, we’ll explore the various ways you can use the print() function to display information, format output, and enhance the user experience.

At its simplest, the print() function is used to display text or variables on the screen. Here’s a basic example:

print.py
print("Hello, Python!")

Output:

command
C:\Users\Your Name> python print.py
Hello, Python!

This single line of code outputs the phrase “Hello, Python!” to the console. You can use single or double quotes to define strings within the print() function.

You can concatenate multiple strings or variables within the print() function:

print.py
name = "Alice"
print("Hello, " + name + "!")

Output:

command
C:\Users\Your Name> python print.py
Hello, Alice!

String interpolation, also known as f-strings (formatted string literals), provides a more concise and readable way to format strings:

print.py
name = "Bob"
age = 30
print(f"{name} is {age} years old.")

Output:

command
C:\Users\Your Name> python print.py
Bob is 30 years old.

F-strings can do much more than insert values — a : inside the braces starts a format specifier that controls width, alignment, decimal places, and more.

fstring_format.py
pi = 3.14159
price = 1234.5
ratio = 0.875
 
print(f"{pi:.2f}")       # 3.14    -> 2 decimal places
print(f"{price:,.2f}")   # 1,234.50 -> thousands separator
print(f"{ratio:.1%}")    # 87.5%   -> percentage
print(f"{42:05d}")       # 00042   -> pad with zeros to width 5
print(f"{'hi':>10}")     # '        hi' -> right-align in 10 cols

You can also print the expression and its value with a trailing = (great for debugging):

fstring_debug.py
x = 10
print(f"{x = }")   # x = 10

The format() method allows for more controlled string formatting:

print.py
name = "Charlie"
age = 25
print("{} is {} years old.".format(name, age))

Output:

command
C:\Users\Your Name> python print.py
Charlie is 25 years old.

By default, the print() function separates items with a space. You can change this using the sep parameter:

print.py
print("One", "Two", "Three", sep="-")

Output:

command
C:\Users\Your Name> python print.py
One-Two-Three

The end parameter defines the character at the end of the print() function:

print.py
print("This is a line", end=".\n")

Output:

command
C:\Users\Your Name> python print.py
This is a line.
print.py
print("This is a line", end="")
print("This is another line")

Output:

command
C:\Users\Your Name> python print.py
This is a lineThis is another line

In this example, we’ve used the end parameter to remove the newline character from the first print() function. This allows us to print the second line on the same line as the first.

Diagram:

diagram print() parameters mermaid
How sep, end, and file shape the output

The * operator unpacks an iterable so each element becomes a separate argument — combine it with sep to format collections neatly:

unpack_print.py
fruits = ["apple", "banana", "cherry"]
print(*fruits, sep=", ")   # apple, banana, cherry

By default print() writes to standard output. Pass file=sys.stderr to send messages to the error stream instead — useful for warnings and logs that should not mix with normal output. The flush=True argument forces the output to appear immediately.

stderr.py
import sys
print("Normal result")
print("Something went wrong", file=sys.stderr)
print("Loading...", end="", flush=True)   # appears at once, no buffering

You can print the values of variables and the result of expressions directly within the print() function:

print.py
x = 5
y = 10
print("The sum of {} and {} is {}.".format(x, y, x + y))

Output:

command
C:\Users\Your Name> python print.py
The sum of 5 and 10 is 15.

Besides printing to the console, you can redirect the output to a file. This is particularly useful when logging information or capturing program output:

print.py
with open("output.txt", "w") as f:
    print("Redirecting output to a file.", file=f)

Output:

command
C:\Users\Your Name> python print.py
output.txt
Redirecting output to a file.

The pprint module provides a way to pretty-print data structures, enhancing readability:

print.py
from pprint import pprint
 
data = {"name": "David", "age": 28, "city": "Techland"}
pprint(data)

Output:

command
C:\Users\Your Name> python print.py
{'age': 28, 'city': 'Techland', 'name': 'David'}

You can use ANSI escape codes to add color to your output for improved visual distinction:

print.py
print("\033[1;31mError:\033[0m Something went wrong.")

Output:

command
C:\Users\Your Name> python print.py
Error: Something went wrong.

Mastering the art of printing in Python is about more than just displaying text. It’s about effectively communicating information, enhancing readability, and creating a positive user experience. Whether you’re a beginner or an experienced developer, understanding the nuances of the print() function and exploring advanced printing techniques can significantly impact the quality of your Python programs.

Experiment with the examples provided, try different formatting options, and explore advanced printing features to elevate your Python coding skills. Happy printing, and may your Python output always be clear, concise, and visually appealing!

For more insights and practical examples, delve into our tutorials on Python Central Hub!


pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading