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

Question:

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))
Asked By: Andy

||

Answers:

Try this:

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

The sum of the series 1 + 2 + 3 + ... + n where n is the user inputted number is:

n(n+1)/2 (see wikipedia.org/wiki/1+2+3+4+…)

We have that the average of a set S with n elements is the sum of the elements divided by n. This gives (n(n+1)/2)/n, which simplifies to (n+1)/2.

So the implementation of the average for your application is:

def sum_average(n):
    return (n + 1) / 2

This has the added benefit of being O(1).

Answered By: zr0gravity7

Your version is not working because the average is always set to the last calculation from the for loop. You should be adding the idx for each iteration and then doing the division after the loop has completed. However, all of that is a waste of time because there is already a function that can do this for you.

Use mean from the statistics module.

from statistics import mean

num = int(input("Enter a number"))

result = mean(list(range(1, num+1)))

print(f'The average of all numbers from 1 to {num} is {result}')

If you are determined to do the logic yourself it would be done as below, if we stick with your intended method. @zr0gravity7 has posted a better method.

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

num = int(input("Enter a number"))

result = SumAverage(num)

print(f'The average of all numbers from 1 to {num} is {result}')  

I’m not recommending this, but it might be fun to note that if we abuse a walrus (:=), you can do everything except the final print in one line.

from statistics import mean

result = mean(list(range(1, (num := int(input("Enter a number: ")))+1)))

print(f'The average of all numbers from 1 to {num} is {result}')
Answered By: OneMadGypsy

I went ahead and wrote a longer version than it needs to be, and used some list comprehension that would slow it down only to give some more visibility in what is going on in the logic.

def SumAverage(n):
    sum=0
    l = [] # initialize an empty list to fill
    n = abs(n) # incase someone enters a negative
    
    # lets fill that list
    while n >= 1:
        l.append(n)
        print('added {} to the list'.format(n), 'list is now: ', l)
        n = n - 1 # don't forget to subtract 1 or the loop will never end!

    # because its enumerate, I like to use both idx and n to indicate that there is an index and a value 'n' at that index
    for idx, n in enumerate(l): 
        sum = sum + n

    # printing it so you can see what is going on here 
    print('length of list: ', len(l))
    print('sum: ', sum)

    return sum/len(l)


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

[its the better plz see this.
(short description):- user enter the list through functions then that list is converted into int. And the average is calculated all is done through functions thanx

]1

Answered By: CRSEV7
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.