Write a Python Function to Calculate Average of given Array, 0 if Negative

In this tutorial, we will learn how to create a function to calculate the average of a given Array, O if negative in Python.

Suppose we have been given the following question:

Question

Write a Python function Average(z) that computes the average of array z. If the computed average is negative it returns 0 else it returns the computed average. The array z is defined with elements as follows:

a) z=[5,9,3,4,5,6]
b) z=[1,2,0,-2,-8]

Solution a)

def Average(z):
    y=np.mean(z)
    if y<0:
        print(0)
    else:
        print(y)
        return(z)
        
a=np.array([5,9,3,4,5,6])
print(a)
b=Average(a)

Output

5.333333333333333

Solution b)

def Average(z):
    y=np.mean(z)
    if y<0:
        print(0)
    else:
        print(y)
        return(z)
        
a=np.array([1,2,0,-2,-8])
print(a)
b=Average(a)

Output

0

Leave a Reply

Your email address will not be published.