Prompt Details
Model
Chat - (gpt-5)
Token size
313 ($0.00978 / call)
Example input
[PASTE YOUR CODE HERE]: def calculate_averagenumbers total = 0 for num in numbers: total = num return total / len(numbers) Example usage data = (10, 20, 30, 40) print(Average:, calculate_average(data)) This will cause an error empty_data = () print("Average:", calculate_average(empty_data))
[DESCRIBE THE PROBLEM HERE]: ZeroDivisionError: division by zero
Example output
Error Summary:
The code crashes when calculating the average of an empty list because it divides by zero.
---
Cause:
When empty_data is passed to calculate_average,
len(numbers) becomes 0.
Division by zero is mathematically undefined, so Python throws a ZeroDivisionError.
The function has no check to handle empty lists before performing division.
---
Fixed Code:
def calculate_average(numbers):
"""
Calculate the average of a list of numbers.
Returns None if the list is empty.
"""
if not numbers: # Check if list is empty
return None # Prevent division by zero
total = sum(numbers) # More Pythonic than loop addition
return total / len(numbers)
# Example usage
data = [10, 20, 30, 40]
print("Average:", calculate_average(data)) # Output: 25.0
empty_data = []
result = calculate_average(empty_data)
if result is None:
print("Average: No data to calculate") # Graceful handling
else:
print("Average:", result)
---
Optimization Notes:
1. Use Built-in Functions โ Replaced manual loop with sum() for better readability and performance.
2. Graceful Error Handling โ Added a check for empty lists to avoid runtime crashes.
3. Return None for No Data โ This makes the functionโs behavior clear when thereโs no input.
4. Docstring Added โ Makes the function self-explanatory.
5. Avoid Magic Errors โ Always check inputs before doing operations like division or indexing.
---
Best Practices to Prevent This in the Future:
Always validate inputs before performing operations.
Write unit tests for edge cases (like empty lists, negative numbers, or unexpected types).
Use type hints (def calculate_average(numbers: list[float]) -> float:) for clarity.
Add docstrings to explain function behavior and edge case handling.
---
By purchasing this prompt, you agree to our terms of service
GPT-5
Tired of errors stopping your code?
This prompt turns ChatGPT into a personal coding doctor that diagnoses errors, fixes bugs, and explains solutions step-by-step โ in any programming language.
๐ Get your code working in minutes, without endless Googling!
๐ Buyer Benefits:
Works for Python, JavaScript, PHP, C++, Java, and more
Explains why the bug happened
Suggests optimized & clean code replacements
Saves hours of frustration
Perfect for students, freelancers, and developers
...more
Added over 1 month ago
