PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Medium
Question 33
You are working on a Python project that involves a series of mathematical operations. You have a function called calculate_sum that takes in an arbitrary number of arguments and is responsible for calculating the sum of those numbers. However, you need to create a separate function called calculate_average that takes the same arguments, calculates the average of the numbers, and utilizes the calculate_sum function to perform the sum calculation. Which of the following code snippets demonstrates the correct implementation of the calculate_average function?
-
A
- def calculate_average(args):
- total_sum = calculate_sum(*args)
- average = total_sum / len(args)
- return average
-
B
- def calculate_average(args):
- total_sum = calculate_sum(args)
- average = total_sum / len(args)
- return average
-
C
- def calculate_average(*args):
- total_sum = calculate_sum(*args)
- average = total_sum / len(args)
- return average
-
D
- def calculate_average(*args):
- total_sum = calculate_sum(args)
- average = total_sum / len(args)
- return average
Reveal correct answer
Correct answer: C
A.
This implementation is missing the * notation in the parameter declaration, so it would expect a single argument.
B.
The calculate_average function is missing the * notation in the parameter declaration, which means it would expect a single argument rather than multiple arguments.
C.
By using the *args notation when calling calculate_sum, we unpack the elements of args and pass them as separate arguments to the calculate_sum function, allowing it to correctly calculate the sum.
D.
In this option, args is already a tuple, so passing it directly to calculate_sum would result in treating the entire tuple as a single argument. This would not give the desired behavior.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
