Learn Before
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
Tags
Ch.3 Prompting - Foundations of Large Language Models
Foundations of Large Language Models
Computing Sciences
Foundations of Large Language Models Course
Learn After
Analyze the following Python code. What is the most likely outcome when it is executed?
def find_mean(data): # Note: This function does not handle all possible inputs total = sum(data) count = len(data) return total / count test_data = [] print(find_mean(test_data))Python Function for List Average
Consider the two Python functions below, both intended to find the average of a list of numbers. Evaluate the primary difference in their design and robustness.
Function A:
def calculate_average_a(numbers): if not numbers: return 0 return sum(numbers) / len(numbers)Function B:
def calculate_average_b(numbers): return sum(numbers) / len(numbers)Which statement best evaluates the two functions?