The print() function is often the first Python command a beginner uses. It displays text, numbers, variables, calculations, and diagnostic information in the standard output, which is normally a terminal or an editor’s console.
This complete guide explains the Python print function from its simplest form to separators, custom line endings, f-strings, alignment, file output, debugging, and the difference between printing, returning, and logging.
Your First print() Call
print("Hello, world!")Python evaluates the value inside the parentheses and writes its text representation to the output. Strings require quotes; numbers do not.
print("Python is readable")
print(42)
print(3.14)
print(10 + 5)The function is one of Python’s built-ins. The built-in functions guide introduces other essential tools such as len(), type(), and input(). The exact signature is documented in the official Python print() reference.
Print Variables
name = "Ava"
age = 24
print(name)
print(age)You can pass several arguments separated by commas. Python converts them to text and inserts a space between them by default.
print("Name:", name, "Age:", age)Using commas is convenient because you do not need to convert numbers manually.
score = 95
print("Score: " + str(score))
print("Score:", score)The sep Parameter
The sep parameter changes the text inserted between multiple arguments.
print("2026", "07", "10", sep="-")
print("home", "user", "project", sep="/")
print("red", "green", "blue", sep=" | ")This is useful for simple output formatting, but for data files use dedicated CSV or JSON tools rather than manually joining complex values.
The end Parameter
By default, print() ends with a newline. Change end to keep the next output on the same line.
print("Loading", end="")
print("...done")You can create counters or progress messages:
for number in range(1, 6):
print(number, end=" ")
print() # finish with a newlineThe Python range() guide explains how the sequence in this loop is generated.
Format Output with f-Strings
F-strings are usually the clearest way to combine text, variables, and expressions.
product = "Keyboard"
price = 89.9
quantity = 3
print(f"Product: {product}")
print(f"Unit price: ${price:.2f}")
print(f"Total: ${price * quantity:.2f}")Anything inside braces is evaluated as a Python expression. Format specifications after a colon control decimals, percentages, width, alignment, and other details.
ratio = 0.8734
large_number = 1250000
print(f"Success rate: {ratio:.1%}")
print(f"Users: {large_number:,}")The article on formatting numbers and currency with f-strings covers these options in depth.
Align Text in Columns
items = [
("Notebook", 1200.00),
("Mouse", 29.90),
("Cable", 8.50),
]
print(f"{'Product':<15} {'Price':>10}")
print("-" * 26)
for product, price in items:
print(f"{product:<15} ${price:>9.2f}")< aligns to the left, > aligns to the right, and ^ centers the value inside the requested width.
Escape Characters
Escape sequences represent characters that are difficult to type directly inside a string.
print("First line\nSecond line")
print("Name\tScore")
print("She said: \"Hello\"")
print("C:\\Users\\Ava\\project")\n: newline.\t: tab.\": a double quote inside a double-quoted string.\\: a literal backslash.
Raw strings are useful for many paths and regular expressions:
print(r"C:\Users\Ava\project")Print Lists and Dictionaries
colors = ["blue", "green", "orange"]
user = {"name": "Sam", "active": True}
print(colors)
print(user)The default representation is useful for inspection. For user-facing output, format the values deliberately.
for position, color in enumerate(colors, start=1):
print(f"{position}. {color.title()}")
for key, value in user.items():
print(f"{key}: {value}")Print to a File
The file parameter sends output to a writable text stream instead of the terminal.
with open("report.txt", "w", encoding="utf-8") as report:
print("Monthly report", file=report)
print("Orders: 128", file=report)
print("Revenue: $4,250.00", file=report)The context manager closes the file even if an error occurs. For structured data, prefer the csv or json modules. The file-handling patterns in the Python with statement guide are also useful when available in the English library.
The flush Parameter
Output may be buffered before it is displayed or written. flush=True asks Python to flush the stream immediately.
import time
for second in range(3, 0, -1):
print(second, end=" ", flush=True)
time.sleep(1)
print("Go!")This can matter for progress messages, subprocess communication, and redirected output.
Use repr for Debugging
A value may contain spaces, newline characters, or empty text that is hard to see. The !r conversion in an f-string displays its developer-oriented representation.
username = " ava\n"
print(f"username={username}")
print(f"username={username!r}")The second line exposes the surrounding spaces and newline. Python also supports a concise debug form:
total = 15 * 4
print(f"{total=}")See debugging Python with f-strings for more examples.
print() vs return
print() displays a value. return sends a value back from a function so other code can use it.
def add_wrong(a, b):
print(a + b)
def add(a, b):
return a + b
result = add(2, 3)
print(result * 10)The first function’s displayed result cannot be multiplied later because the function implicitly returns None. The Python functions guide explains return values and function design.
print() vs logging
Temporary prints are useful while learning and debugging. Larger applications benefit from the logging module because it supports levels, timestamps, files, formatters, and configurable destinations.
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Application started")
logging.warning("Stock is low")
logging.error("Payment failed")Do not print passwords, tokens, private user data, or full payment information. Logs and terminal output may be stored or shared.
Common Mistakes
Missing Parentheses
# Incorrect in Python 3
print "Hello"
# Correct
print("Hello")Unclosed Quotes
# SyntaxError
print("Hello)
# Correct
print("Hello")Joining Text and Numbers with +
age = 25
# TypeError
# print("Age: " + age)
print("Age:", age)
print(f"Age: {age}")Printing a Function Instead of Calling It
def greet():
return "Hello"
print(greet) # function object
print(greet()) # returned textPractical Example: Receipt
cart = [
("Coffee", 8.50, 2),
("Bread", 4.00, 1),
("Milk", 5.25, 3),
]
grand_total = 0
print("=" * 40)
print(f"{'ITEM':<14}{'QTY':>5}{'UNIT':>9}{'TOTAL':>12}")
print("-" * 40)
for name, unit_price, quantity in cart:
total = unit_price * quantity
grand_total += total
print(f"{name:<14}{quantity:>5}{unit_price:>9.2f}{total:>12.2f}")
print("-" * 40)
print(f"{'Grand total':<28}${grand_total:>11.2f}")
print("=" * 40)This combines loops, tuple unpacking, calculations, alignment, and numeric formatting.
Frequently Asked Questions
Can print() display any object?
It can display the string representation of almost any Python object. Custom classes can define __str__() and __repr__() to improve that representation.
How do I print without a newline?
Pass a different end value, such as print("Loading", end="").
How do I print several values with no spaces?
Use sep="", an f-string, or build the final string before printing.
Why does print() show None?
You may be printing the result of a function that does not return a value, or printing the return value of a method that modifies an object in place.
Should production applications use print()?
Use it for intentional command-line output. For diagnostic records in long-running applications, structured logging is usually more appropriate.
Conclusion
Python’s print() function is simple but flexible. Learn its arguments, combine it with f-strings, use alignment for readable terminal output, redirect output when appropriate, and distinguish display from return values. These skills make beginner programs clearer and provide a strong foundation for debugging and command-line applications.






