Practical Code Examples
Real-World Scenarios
Exploring practical applications helps developers understand the nuanced differences between print()
and return
.
Example 1: Data Processing
def calculate_average(numbers):
print(f"Processing {len(numbers)} numbers") ## Logging
total = sum(numbers)
average = total / len(numbers)
print(f"Calculation complete") ## Additional logging
return average ## Actual result
data = [10, 20, 30, 40, 50]
result = calculate_average(data) ## Returns 30.0
Example 2: Error Handling
def divide_numbers(a, b):
try:
print(f"Attempting to divide {a} by {b}")
result = a / b
return result
except ZeroDivisionError:
print("Error: Division by zero!")
return None
Function Behavior Visualization
graph TD
A[Function Call] --> B{Input Validation}
B -->|Valid| C[Process Data]
C --> D[Print Logs]
C --> E[Return Result]
B -->|Invalid| F[Handle Error]
F --> G[Print Error Message]
F --> H[Return None/Error]
Common Patterns
Pattern |
Print Usage |
Return Usage |
Logging |
Track execution steps |
Provide computed value |
Debugging |
Display intermediate values |
Send final result |
Error Handling |
Show error messages |
Return status/result |
def transform_data(raw_data):
print("Starting data transformation")
## Data validation
if not raw_data:
print("Warning: Empty data set")
return []
## Transformation logic
transformed = [x * 2 for x in raw_data]
print(f"Transformed {len(raw_data)} items")
return transformed
original = [1, 2, 3, 4, 5]
processed = transform_data(original) ## Returns [2, 4, 6, 8, 10]
Best Practices for LabEx Developers
- Use
print()
for logging and debugging
- Use
return
for sending actual results
- Combine both for comprehensive function design
- Handle potential errors gracefully
By mastering these techniques, Python programmers can create more robust and informative code.