Python Forum
Trouble with Average Calculation Despite Error Handling
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trouble with Average Calculation Despite Error Handling
#1
def compute_average(data):
    try:
        total_sum = sum(data)
        avg = total_sum / len(data)
        return avg
    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)

data = [12, 24, 36, 48, 60]
average_result = compute_average(data)
print("The average is:", average_result)
Despite implementing error handling in my code, I'm still encountering issues. The program runs without any errors, but the average is not being calculated correctly. Can you help me identify what's wrong?
Reply
#2
When I run your code it prints 36, the correct answer. What answer do you get?
Reply
#3
```python
# Function to compute the average of a list of numbers
def compute_average(data):
    try:
        total_sum = sum(data)  # Calculate the sum of elements in data
        avg = total_sum / len(data)  # Calculate the average
        return avg  # Return the computed 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)

# Example data list
data = [12, 24, 36, 48, 60]

# Compute the average using the function
average_result = compute_average(data)

# Print the computed average
print("The average is:", average_result)
```
This Python code defines a function compute_average(data) that attempts to compute the average of a list of numbers (data). Inside the function:

- It tries to calculate the sum of data using sum(data).
- It then computes the average by dividing the total sum by the length of data.
- If there's a ZeroDivisionError, it handles it by printing an error message.
- If there's a TypeError (e.g., if data is not a list of numbers), it also prints an error message.
- Any other unexpected exceptions are caught and their error message is printed.

The provided example data list [12, 24, 36, 48, 60] should correctly compute and print the average, which is 36.0. If you're experiencing issues where the average is not calculated correctly, ensure that data contains only numeric values (ints or floats) and that it's not empty. Also, ensure you're using Python 3.x or higher for consistent float division behavior.

Also, check out the latest Python Developer Jobs in 2024. Keep your skills updated, build projects, and network within the community to improve your chances of finding a suitable job.
Reply
#4
I tried to execute your code and the result is 36, which is correct.
You can verify here: https://pythononline.net/#Vc9rDU

What do you mean by "The program runs without any errors, but the average is not being calculated correctly." ??
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Calculating Average with Error Handling mikasa 7 856 May-07-2024, 07:48 AM
Last Post: snippsat
Star python exception handling handling .... with traceback mg24 3 1,460 Nov-09-2022, 07:29 PM
Last Post: Gribouillis
  Help needed with a "for loop" + error handling tamiri 2 2,933 May-27-2022, 12:21 PM
Last Post: tamiri
  Handling Python Fatal Error richajain1785 7 6,346 Oct-14-2021, 01:34 PM
Last Post: Tails86
  Error Handling JarredAwesome 5 3,191 Oct-17-2020, 12:41 AM
Last Post: JarredAwesome
  Error handling using cmd module leifeng 3 3,169 Jun-06-2020, 06:25 PM
Last Post: leifeng
  Excpetion Handling Getting Error Number gw1500se 4 2,591 May-29-2020, 03:07 PM
Last Post: gw1500se
  python Calculation error: 39.8-0.1=39.699999999999996 wei 2 2,220 Jun-10-2019, 10:22 AM
Last Post: wei
  Calculation Inside Dictionary Error prophet11 3 2,773 Apr-22-2019, 05:23 AM
Last Post: perfringo
  Warning / Error handling in python Prarthana_12 1 5,265 Feb-08-2019, 09:21 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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