If you're just starting out in programming, the print() function will likely be the first one you'll use in Python. This fundamental function allows you to display text, variables, and results directly in the console, making it an indispensable tool for developing and debugging your programs.
Mastering print() is essential for any Python developer, whether beginner or experienced. This function will accompany you throughout your learning journey, especially if you follow our complete Python course. In this article, we'll explore in depth all the possibilities offered by this essential function.
š” The print() function is often a developer's first contact with Python. It allows you to instantly visualize the result of your instructions!
Definition and basic syntax
What is the print() function?
The print() function is a Python built-in function that displays information to the standard output, usually the console or terminal. It automatically converts objects to strings before displaying them, making it extremely versatile.
Unlike some programming languages where displaying output can be complex, Python makes this operation simple and intuitive through print().
Complete syntax
Here is the complete signature of the print() function:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)This syntax may seem intimidating at first, but don't worry: we'll break down each parameter in detail.
Parameters explained
| Parameter | Description | Default value |
|---|---|---|
*objects | Objects to display (can be multiple) | None |
sep | Separator between objects | Space ' ' |
end | Character added at the end | Newline '\n' |
file | Output stream | sys.stdout |
flush | Force immediate writing | False |
Basic practical examples
Displaying simple text
Let's start with the most basic use of print(): displaying a string.
# Display a simple message
print("Welcome to Believemy!")
# Display with single quotes
print('Learn Python easily')
# Display an empty string (creates an empty line)
print()These examples will produce the following outputs in your console:
Welcome to Believemy!
Learn Python easily
Displaying variables
The print() function is particularly useful for displaying the value of your variables. Python automatically converts different data types to displayable text.
# Variables of different types
course_name = "Python"
number_of_students = 1500
price = 49.99
is_available = True
# Display each variable
print(course_name) # Displays: Python
print(number_of_students) # Displays: 1500
print(price) # Displays: 49.99
print(is_available) # Displays: TrueDisplaying multiple elements
You can pass multiple arguments to print(), which will display them separated by spaces by default.
# Combine text and variables
student = "Marie"
points = 850
print("Congratulations", student, "! You have", points, "points.")
# Displays: Congratulations Marie ! You have 850 points.Warning: each argument passed to print() is automatically converted to a string. This works with most types, but some custom objects may require a __str__() method for correct display.
Advanced formatting with print()
F-strings (modern formatting)
Since Python 3.6, f-strings are the recommended method for formatting your strings. They are readable, performant, and very convenient.
# Using f-strings
course = "Python"
duration_hours = 40
level = "beginner"
print(f"The {course} course lasts {duration_hours} hours.")
print(f"It is suitable for {level} level.")
# Expressions in f-strings
price_excl_tax = 100
vat = 0.20
print(f"Price incl. tax: {price_excl_tax * (1 + vat):.2f} ā¬")
# Displays: Price incl. tax: 120.00 ā¬F-strings also allow you to execute expressions directly inside the curly braces, as we see with the tax-inclusive price calculation.
The format() method
Before f-strings, the format() method was the reference for string formatting. It remains useful in certain contexts.
# Formatting with format()
print("Hello {}! Welcome to {}".format("Alice", "Believemy"))
# With indices
print("{0} is learning {1}. {0} is progressing fast!".format("Lucas", "Python"))
# With names
print("{name} is taking the {course} course".format(name="Emma", course="Python"))The % operator (legacy method)
This C-inherited syntax is still present in older code, but we recommend using f-strings for all new projects.
# Formatting with %
name = "Believemy"
year = 2024
print("Welcome to %s in %d" % (name, year))
# %s for strings, %d for integers, %f for floatsCustomizing print() behavior
The sep parameter (separator)
By default, print() separates arguments with a space. The sep parameter allows you to customize this separator.
# Default separator (space)
print("Python", "Java", "JavaScript")
# Displays: Python Java JavaScript
# Custom separator
print("Python", "Java", "JavaScript", sep=" | ")
# Displays: Python | Java | JavaScript
# Separator with newline
print("Step 1", "Step 2", "Step 3", sep="\n")
# Displays:
# Step 1
# Step 2
# Step 3
# No separator
print("B", "e", "l", "i", "e", "v", "e", "m", "y", sep="")
# Displays: BelievemyThe end parameter (line ending)
The end parameter defines what is added after the display. By default, it's a newline (\n).
# Default behavior
print("Line 1")
print("Line 2")
# Displays:
# Line 1
# Line 2
# Prevent newline
print("Loading", end="")
print(".", end="")
print(".", end="")
print(".")
# Displays: Loading...
# Custom ending
print("Progress", end=" -> ")
print("Done!")
# Displays: Progress -> Done!šÆ Tip: combine sep and end to create customized displays, such as progress bars or interactive menus!
Writing to a file with file
The file parameter allows you to redirect output to a file instead of the console.
# Write to a file
with open("believemy_log.txt", "w") as file:
print("Session started", file=file)
print("User connected", file=file)
print("Python course started", file=file)
# The file will contain:
# Session started
# User connected
# Python course startedThe flush parameter
By default, Python buffers outputs to optimize performance. The flush=True parameter forces immediate writing.
import time
# Without flush - may not display immediately
for i in range(5):
print(f"Step {i+1}/5", end="\r")
time.sleep(1)
# With flush - guaranteed immediate display
for i in range(5):
print(f"Step {i+1}/5", end="\r", flush=True)
time.sleep(1)Common use cases
Simple debugging
One of the most frequent uses of print() is quick debugging of your code.
def calculate_average(grades):
print(f"DEBUG: Grades received = {grades}") # Check input
if not grades:
print("DEBUG: Empty list detected") # Checkpoint
return 0
total = sum(grades)
print(f"DEBUG: Total = {total}") # Check calculation
average = total / len(grades)
print(f"DEBUG: Average = {average}") # Check result
return average
# Test
result = calculate_average([15, 18, 12, 16])For more advanced debugging, consider using Python's logging module or a debugger integrated into your IDE. The print() function is perfect for quick checks but can become difficult to manage in complex projects.
Displaying data structures
The print() function works perfectly with Python data structures like list, dict, and tuple.
# Display a list
courses = ["Python", "JavaScript", "React"]
print(courses)
# Displays: ['Python', 'JavaScript', 'React']
# Display a dictionary
student = {
"name": "Sophie",
"level": "intermediate",
"points": 1200
}
print(student)
# Displays: {'name': 'Sophie', 'level': 'intermediate', 'points': 1200}
# Display a tuple
coordinates = (48.8566, 2.3522)
print(coordinates)
# Displays: (48.8566, 2.3522)Formatted display with pprint
For more readable display of complex structures, the pprint (pretty print) module is recommended.
from pprint import pprint
course_data = {
"title": "Complete Python Course",
"modules": [
{"name": "Introduction", "duration": 2},
{"name": "Variables and types", "duration": 3},
{"name": "Control structures", "duration": 4},
{"name": "Functions", "duration": 5}
],
"level": "beginner",
"price": 49.99
}
# With standard print
print(course_data)
# With pprint (more readable)
pprint(course_data)Best practices and common mistakes
Best practices
Here are recommendations for using print() professionally:
- Use f-strings for formatting: they are more readable and more performant
- Remove debug print() statements before putting your code in production
- Prefer the logging module for professional applications
- Document your outputs with clear labels (e.g.,
print(f"Result: {value}")) - Use comment to explain temporary print() calls
Common mistakes to avoid
# ā Error: missing parentheses (Python 2 vs Python 3)
# print "Hello" # SyntaxError in Python 3
# ā
Correct
print("Hello")
# ā Error: concatenating different types
age = 25
# print("I am " + age + " years old") # TypeError
# ā
Correct: use f-string or str()
print(f"I am {age} years old")
print("I am " + str(age) + " years old")
# ā Error: forgetting commas between arguments
# print("A" "B" "C") # Displays: ABC (implicit concatenation)
# ā
Correct: with commas
print("A", "B", "C") # Displays: A B CPrint vs return
A common confusion among beginners concerns the difference between print() and return in functions defined with def.
# print() displays but returns nothing
def display_sum(a, b):
print(a + b) # Displays the result
# Returns nothing (returns None implicitly)
# return returns a usable value
def calculate_sum(a, b):
return a + b # Returns the result
# Demonstrating the difference
result1 = display_sum(5, 3) # Displays: 8
print(f"Result 1: {result1}") # Displays: Result 1: None
result2 = calculate_sum(5, 3) # Displays nothing
print(f"Result 2: {result2}") # Displays: Result 2: 8š Remember: print() is used to display information for the user or developer, while return is used to send back a value that can be used elsewhere in the program.
Advanced print() usage
Creating a progress bar
Thanks to the end and flush parameters, you can create dynamic displays.
import time
def progress_bar(total):
for i in range(total + 1):
percentage = (i / total) * 100
bar = "ā" * i + "ā" * (total - i)
print(f"\r[{bar}] {percentage:.0f}%", end="", flush=True)
time.sleep(0.1)
print() # Newline at the end
# Usage
print("Downloading the course...")
progress_bar(20)
print("Download complete!")Colored display in terminal
You can use ANSI codes to add color to your displays.
# ANSI color codes
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
RESET = "\033[0m"
print(f"{GREEN}ā Success: Python course completed!{RESET}")
print(f"{RED}ā Error: File not found{RESET}")
print(f"{YELLOW}ā Warning: This action is irreversible{RESET}")
print(f"{BLUE}ā¹ Info: New update available{RESET}")Redefining print() (not recommended)
It's technically possible to redefine print(), but this practice is strongly discouraged as it can create unexpected behavior.
# For educational purposes only - DO NOT DO IN PRODUCTION
original_print = print
def print(*args, **kwargs):
original_print("[LOG]", *args, **kwargs)
print("Test message")
# Displays: [LOG] Test message
# Restore original behavior
print = original_printFrequently asked questions about print()
What is the difference between print() in Python 2 and Python 3?
In Python 2, print was a statement and was written without parentheses: print "Hello". In Python 3, print() became a full-fledged function, requiring parentheses. This evolution allowed adding the sep, end, file, and flush parameters, making the function much more flexible.
How do I display special characters like quotes?
You can use escape sequences with the backslash \, or alternate between single and double quotes:
# With escape sequences
print("He said: \"Hello!\"")
print('It\'s easy')
# By alternating quotes
print('He said: "Hello!"')
print("It's easy")How can I learn Python?
To master Python and all its subtleties, including advanced use of print() and many other concepts, we recommend following our complete Python course. You'll discover the basics of the language, data structures, object-oriented programming with class, and much more, all accompanied by practical exercises and concrete projects.