Skip to content
Related Articles

Related Articles

Find the average of an unknown number of inputs in Python
  • Last Updated : 29 Dec, 2020

Prerequisites: *args and **kwargs in Python

The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args. In this article, the task is to find the average of the unknown number of inputs.

Examples:

Input : 1, 2, 3
Output : 2.00

Input : 2, 6, 4, 8
Output: 5.00

Below is the implementation.




   
  
# function that takes arbitary
# number of inputs
def avgfun(*n):
    sums = 0
  
    for t in n:
        sums = sums + t
  
    avg = sums / len(n)
    return avg
      
  
# Driver Code 
result1 = avgfun(1, 2, 3)
result2 = avgfun(2, 6, 4, 8)
  
# Printing average of the list 
print(round(result1, 2))
print(round(result2, 2))

Output:

2.0
5.0

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :