Python Code Examples
Basic Average Calculation
def simple_average(a, b):
return (a + b) / 2
## Example usage
print(simple_average(10, 20)) ## Output: 15.0
Handling Different Data Types
def flexible_average(*args):
"""Compute average for multiple number types"""
return sum(args) / len(args)
## Integer example
print(flexible_average(5, 10)) ## Output: 7.5
## Float example
print(flexible_average(3.5, 4.5)) ## Output: 4.0
Error Handling Approach
def safe_average(num1, num2):
try:
return (num1 + num2) / 2
except TypeError:
print("Invalid input: Numbers required")
return None
## Safe calculation examples
print(safe_average(10, 20)) ## Valid input
print(safe_average('5', 10)) ## Invalid input
Advanced Averaging Techniques
def weighted_average(num1, num2, weight1=0.5, weight2=0.5):
"""Compute weighted average"""
return (num1 * weight1) + (num2 * weight2)
## Example usage
print(weighted_average(10, 20)) ## Default equal weights
print(weighted_average(10, 20, 0.3, 0.7)) ## Custom weights
Computation Workflow
graph TD
A[Input Numbers] --> B[Validate Input]
B --> C[Perform Calculation]
C --> D[Return Average]
D --> E[Display Result]
Method |
Time Complexity |
Memory Usage |
Flexibility |
Simple Average |
O(1) |
Low |
Basic |
Flexible Average |
O(n) |
Moderate |
High |
Weighted Average |
O(1) |
Low |
Advanced |
Best Practices
- Use type hints
- Implement error checking
- Consider performance requirements
At LabEx, we emphasize writing clean, efficient, and robust Python code for average calculations.