Learn Before
Code

Python Function to Calculate the Average of a List

This Python function, calculate_average, computes the average of a list of numbers. It first checks if the list is empty. If the list contains numbers, it calculates the average by dividing the sum of the numbers, found using the built-in sum() function, by the count of the numbers, determined by the len() function. To prevent a ZeroDivisionError, the function returns 0 if the input list is empty.

def calculate_average(numbers): """ Calculates the average of a list of numbers. Returns 0 if the list is empty. """ if numbers: # Check if the list is not empty return sum(numbers) / len(numbers) else: return 0 # Example 1: Non-empty list my_numbers = [10, 20, 30, 40, 50] average = calculate_average(my_numbers) print(f"The average is: {average}") # Expected Output: The average is: 30.0 # Example 2: Empty list empty_list = [] average_empty = calculate_average(empty_list) print(f"The average of an empty list is: {average_empty}") # Expected Output: The average of an empty list is: 0

0

1

Updated 2025-10-07

Contributors are:

Who are from:

Tags

Ch.3 Prompting - Foundations of Large Language Models

Foundations of Large Language Models

Computing Sciences

Foundations of Large Language Models Course