Output Variables
Basic Output Methods
The built-in print() function is the most common way to display variables in Python. You can pass single values, multiple values separated by commas, or use formatting techniques like f-strings, str.format(), or the older % operator.
# print() function
name = "Alice"
age = 25
print(name) # Simple output
print("Name:", name) # Multiple items
print(f"{name} is {age}") # f-string (Python 3.6+)
# String formatting
print("{} is {}".format(name, age)) # .format() method
print("%s is %d" % (name, age)) # Old % formatting
Alice Name: Alice Alice is 25 Alice is 25 Alice is 25
Advanced Output Techniques
Formatting options let you control precision, base representations, and alignment of variables in output. f-strings and format specifiers provide flexible, readable ways to style output.
# Formatting numbers
pi = 3.14159265
print(f"Pi: {pi:.2f}") # 2 decimal places
print(f"Hex: {255:x}") # Hexadecimal
print(f"Scientific: {1000:.2e}") # Scientific notation
# Column alignment
data = [("Alice", 25), ("Bob", 30), ("Charlie", 35)]
for name, age in data:
print(f"{name:<10} | {age:>5}") # Left/right align
Pi: 3.14 Hex: ff Scientific: 1.00e+03 Alice | 25 Bob | 30 Charlie | 35
Output to Files
You can direct output to files using the print() function with the `file` argument, or by temporarily redirecting `sys.stdout`. The `with` statement ensures files are properly closed after writing.
# Writing to a text file
with open('output.txt', 'w') as f:
print(f"User: {name}", file=f)
print(f"Age: {age}", file=f)
# Redirecting stdout
import sys
original_stdout = sys.stdout
with open('log.txt', 'w') as f:
sys.stdout = f
print("This goes to the file")
sys.stdout = original_stdout
Debugging Output
For debugging, Python offers additional output tools. pprint prints nested structures in a readable format, repr() shows technical representations, logging is suited for applications, and vars() reveals an object's attributes.
from pprint import pprint
complex_data = {
'users': [
{'id': 1, 'name': 'Alice', 'roles': ['admin', 'user']},
{'id': 2, 'name': 'Bob', 'roles': ['user']}
]
}
pprint(complex_data, indent=2, width=50)
Method | Use Case |
---|---|
print() | Simple debugging |
pprint() | Pretty-print complex data structures |
logging | Configurable output in production |
repr() | Technical string representation |
vars() | Inspect object attributes |