Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ZeroDivisionError
#1
# Trouble in the code
def calculate_average(numbers):
    try:
        total = sum(numbers)
        average = total / len(numbers)
        return average
    except ZeroDivisionError:
        print("Error: Division by zero occurred.")
    except TypeError:
        print("Error: Input must be a list of numbers.")
    except Exception as e:
        print("An unexpected error occurred:", e)

numbers = [10, 20, 30, 40, 50]
result = calculate_average(numbers)
print("The average is:", result)
Despite having implemented error handling, I'm still encountering issues. The program seems to run without any errors, but the average is not being calculated correctly. Can you help me identify what's wrong?
Buckshot Roulette
Reply
#2
Works fine when I run it. Can you provide an example where it returns an incorrect result?

When I call the function with numbers = [] the program prints the error message and returns None. Do you want it to do something different?

Generally, functions that produce a result should return a result or raise an exception. Printing an error message makes the function less useful because the user my wish to do different error handling. You should either do this:
def calculate_average(numbers):
    """Return average of numbers.  Returns None if average cannot be computed."""
    try:
        return sum(numbers) / len(numbers)
    except (ZeroDivisionError, TypeError):
        pass
Or this:
def calculate_average(numbers):
   """Return average of numbers.  Raises TypeError if average cannot be computed."""
    try:
        return sum(numbers) / len(numbers)
    except ZeroDivisionError as ex:
        raise TypeError("numbers cannot be an empty list.") from ex
    except TypeError as ex:
        raise TypeError("numbers must be a list of numbers.") from ex
It is up to the caller to do the exception handling, not the function.
import traceback

for numbers in ((1, 2, 3), (1, '2', 3), [], 5):
    try:
        print(f"calculate_average({numbers}) = ", end="")
        print(calculate_average(numbers))
    except TypeError:
        print("")
        traceback.print_exc()
        print("\n\n")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I try to import Vpython and I get a "ZeroDivisionError" Jon2222 16 2,787 Jul-26-2023, 07:37 AM
Last Post: Jon2222
  Overcoming ZeroDivisionError: division by zero Error dgrunwal 8 5,144 Jun-12-2020, 01:52 PM
Last Post: dgrunwal
  ZeroDivisionError CIVILmath 2 2,549 Jan-17-2019, 02:38 AM
Last Post: CIVILmath

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020