Practical Printing Examples
Basic Printing Techniques
## Simple print statements
print("Hello, LabEx!")
print("Multiple", "arguments", "separated")
## Print with separator and end parameters
print("Python", "Programming", sep="-", end="!\n")
Printing Complex Data Structures
## Printing lists
fruits = ["apple", "banana", "cherry"]
print("Fruits:", fruits)
## Printing dictionaries
user = {"name": "LabEx User", "age": 25}
print("User Details:", user)
## Creating tabular output
students = [
{"name": "Alice", "score": 95},
{"name": "Bob", "score": 87},
{"name": "Charlie", "score": 92}
]
print("Student Performance Report")
print("-" * 30)
for student in students:
print(f"{student['name']:<10} | Score: {student['score']:>3}")
Error and Debug Printing
## Printing to stderr
import sys
print("Error message", file=sys.stderr)
## Debugging with print
debug_mode = True
def debug_print(message):
if debug_mode:
print(f"[DEBUG] {message}")
Printing Techniques Comparison
Technique |
Use Case |
Pros |
Cons |
Basic Print |
Simple output |
Easy to use |
Limited formatting |
F-String Print |
Complex formatting |
Readable |
Python 3.6+ only |
format() Print |
Flexible formatting |
Works on older Python |
More verbose |
Advanced Printing Flow
graph TD
A[Input Data] --> B{Printing Method}
B --> |Simple Print| C[Basic Output]
B --> |Formatted Print| D[Structured Output]
B --> |Debug Print| E[Diagnostic Information]
D --> F[Readable Presentation]
Logging Integration
import logging
## Configure logging
logging.basicConfig(level=logging.INFO)
## Different logging levels
logging.debug("Detailed information")
logging.info("General information")
logging.warning("Warning message")
logging.error("Error occurred")
## Efficient printing for large data
import sys
## Writing directly to stdout
sys.stdout.write("Efficient output\n")
sys.stdout.flush()
Best Practices
- Use f-strings for readable formatting
- Leverage print() parameters
- Consider logging for serious applications
- Be mindful of performance with large outputs
These practical examples demonstrate the versatility of printing in Python, from simple output to complex formatting and logging.