Forum in maintenance, we will back soon 🙂
Functions Lesson
In the functions lesson, I don't understand how to do the exercise calculate_average. Can someone explain it to me?
@butch-berry do you understand what an average is? Let's assume you have a set of five numbers; 1, 2, 3, 4, 5. Now if you add this set of numbers you will have an answer of 15. If you divide the answer by the number of items in the set (5 in this example) you will get the average; 15 / 5 = 3.
If this doesn't satisfy your confusion then please explain what you're confused about.
Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack
@ssadvisor I don't get how to code this
Â
Exercise : Now, your task is to create a function called calculate_average
 that takes a list of numbers as an argument and returns their average. Test your function with different lists of numbers to ensure it works correctly.
Here’s a skeleton to get you started:
@butch-berry I think maybe you need to review the lesson again. I'd be happy to give you 1-on-1 lessons, see the link in my signature to schedule some time.
Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack
Hi Friend,
1. Understanding the Task
- Goal: Create a function named
calculate_average
. - Input: A list of numbers (e.g.,
[1, 2, 3, 4, 5]
). - Output: The average of these numbers.
Average: Calculated by adding all numbers and then dividing by the count of numbers.
2. Steps to Create the Function
- Define the function with a name
calculate_average
and a parameternumbers
for the list. - Calculate the sum of all numbers in the list. You can use the
sum()
function in Python. - Find the length of the list using the
len()
function. This gives you the count of numbers in the list. - Calculate the average by dividing the sum by the length.
- Return the average from the function.
Solution:
def calculate_average(numbers): # Calculate the sum of the numbers total_sum = sum(numbers) # Divide the sum by the length of the numbers list to get the average average = total_sum / len(numbers) # Return the average return average numbers = [1, 2, 3, 4, 5] print(calculate_average(numbers)) # This should print the average of the numbers in the list
Â
Explanation
sum(numbers)
: Adds up all numbers in the list.len(numbers)
: Counts how many numbers are in the list.average = total_sum / len(numbers)
: Calculates the average.return average
: Sends back the calculated average to wherever the function was called.
@admin I met with @butch-berry to help him understand what to do. It was a great session and I was happy to do that.
Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack