Calculate Average in Python

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, calculating the average of a set of numbers is a common task. In this challenge, you will be asked to write a function that takes in two or more numbers and returns their average.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FunctionsGroup -.-> python/keyword_arguments("`Keyword Arguments`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13589{{"`Calculate Average in Python`"}} python/keyword_arguments -.-> lab-13589{{"`Calculate Average in Python`"}} python/lists -.-> lab-13589{{"`Calculate Average in Python`"}} python/tuples -.-> lab-13589{{"`Calculate Average in Python`"}} python/function_definition -.-> lab-13589{{"`Calculate Average in Python`"}} python/build_in_functions -.-> lab-13589{{"`Calculate Average in Python`"}} end

Average

Write a function called average that takes in two or more numbers and returns their average. Your function should follow these guidelines:

  • Use sum() to sum all of the args provided, divide by len().
  • The function should be able to handle any number of arguments.
  • The function should return a float.
def average(*args):
  return sum(args, 0.0) / len(args)
average(*[1, 2, 3]) ## 2.0
average(1, 2, 3) ## 2.0

Summary

In this challenge, you have written a function that calculates the average of two or more numbers. You have used the sum() function to add up all of the numbers and then divided by the number of arguments using len(). This is a useful function to have in your Python toolbox for future projects.

Other Python Tutorials you may like