Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate average in python

I’ve made this console application and it works…but only when you enter small numbers in the input like 1 in ‘ifrom’, 2 in ‘step’ and 3 in ‘to’…but when I enter bigger numbers in ‘to’ for example 100 it just do nothing!!! It even doesn’t give me any error!
Thanks!

print("---Average2---"+"\n")

sum=0
average=0
counter=0

while True:
    ifrom=int(input("From: "))
    step=int(input("Step: "))
    to=int(input("To: "))
    while sum<=to:
        sum=ifrom+step
        counter+=1
        if sum==to:
            print("\n"+"The sum is: ",sum)
            average=sum/counter
            print("The average is: ",average,"\n")
            sum=0
            average=0
            counter=0
            break

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can remove the nested while loop by using built-in Python functions like range():

print("---Average2---"+"\n")

s=0
average=0
counter=0

while True:
    ifrom=int(input("From: "))
    step=int(input("Step: "))
    to=int(input("To: "))
    
    l = list(range(ifrom, to, step))
    s = sum(l)
    average = s/len(l)
    print("\n"+"The sum is: ",s)
    print("The average is: ",average,"\n")
    break

Output: Note that the last number of the range to is not inclusive

---Average2---

From: 0
Step: 1
To: 10

The sum is:  45
The average is:  4.5 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading