[SOLVED] Using a function calculate and display the average of all numbers from 1 to the number entered by the user in python

Issue

I am gitting stuck here, please help. The code has to promt the user to enter a number, pass the number to a python function and let the function calculate the average of all the numbers from 1 to the number entered by the user.


def SumAverage(n):
    sum=0
    for idx in range(1,n+1):
        average =sum/idx 
    return average


num =int(input("Enter a number"))
result=SumAverage(num)
print("The average of all numbers from 1 to {} is {}".format(num,result))

Solution

Try this:

def SumAverage(n):
    sum=0
    for i in range(1,n+1):
        sum += i
    average = sum/n
    return average

Answered By – Luke Weiler

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *