Python Average Function Hackerrank Solution

We have a function called avg that takes in a variable number of integer inputs. We have to complete it such that it returns the average of all the input integers.

def avg(*nums):
   pass

This is the function that we need to complete.

The *args is a special syntax in python used to define a variable number of inputs. Having a * before the name of the argument means it is a variable input. All the inputs are available in this argument as a list

avg(1,2,3,4) means that the nums will be [1,2,3,4]. we can use this to calculate the average.

Code for Python Average Function Hackerrank Solution

def avg(*nums):
    sum = 0
    length = 0

    for n in nums:
        sum += n
        length += 1

    return sum/length

print(avg(1,2,3,4,5))

Output:

3.0

Single Line Code

We can also write the code in a single line using python

def avg(*nums):
    return sum(nums)/len(nums)

print(avg(1,2,3,4,5))

Output:

3.0


Also Read:

Share:

Author: Ayush Purawr