Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Operators and Expressions

Calculate the average of a list of numbers - Python Program

Example 1:

numbers = [10, 20, 30, 40, 50] average = sum(numbers) / len(numbers) print("Average:", average)

Output

 
OUTPUT  :
Average: 30.0
 

Example 2:

def calculate_average(numbers): """ Calculates the average of a list of numbers. Args: numbers: A list of numeric values (integers or floats). Returns: The average of the numbers in the list. Returns 0 if the list is empty to prevent division by zero errors. """ if not numbers: # Check if the list is empty return 0 total_sum = sum(numbers) count = len(numbers) average = total_sum / count return average # Example usage: my_list = [10, 20, 30, 40, 50] avg = calculate_average(my_list) print(f"The list of numbers: {my_list}") print(f"The average of the numbers is: {avg}") empty_list = [] avg_empty = calculate_average(empty_list) print(f"\nThe list of numbers: {empty_list}") print(f"The average of the numbers is: {avg_empty}")

Output

 
OUTPUT  :
The list of numbers: [10, 20, 30, 40, 50]
The average of the numbers is: 30.0

The list of numbers: []
The average of the numbers is: 0
 

Explanation

  • calculate_average(numbers)function:
    • This function takes one argument, numbers, which is expected to be a list containing numeric values.
    • Empty list handling:It first checks if the input numbers list is empty using if not numbers:. If it's empty, it returns 0 to avoid a ZeroDivisionError when attempting to divide by the length of an empty list.
    • Summation:total_sum = sum(numbers) calculates the sum of all elements in the numbers
    • Counting elements:count = len(numbers) determines the number of elements (the length) in the numbers
    • Average calculation:average = total_sum / count performs the division to compute the average.
    • Return value:The calculated average is returned.
  • Example Usage:
    • A sample list my_listis created with integer values.
    • The calculate_averagefunction is called with my_list, and the result is stored in the avg
    • The original list and its calculated average are printed using an f-string for clear output.
    • An empty_listis also tested to demonstrate the handling of empty input.