简体   繁体   中英

how would i find the average when using a 'while' loop in python using this code?

how would i find the average when using a 'while' loop in python using this code?

 n1 = int (input("Enter a value up 100, enter 0 when finished"))
 high =n1

while n1!=0:
     if n1 > high:
     high=n1
     n1 = int(input("Enter another number"))

this sections keeps telling the user to enter values, from here on i dont know how to work out the mean.

Just keep track of the sum and the total_count , and then you can compute the mean whenever you need to.

n1 = int (input("Enter a value up 100, enter 0 when finished"))
high = n1
total_count = 0
sum = 0

while n1 != 0:
    count += 1
    sum += n1
    if n1 > high:
        high=n1
    n1 = int(input("Enter another number"))

If you add a counter variable in your while loop, that is:

while n1 != 0:
    loopCounter += 1

You would get the amount of numbers inputted, and you also need the total of all the numbers inputted, as you know. You could do a similar thing inside the loop:

while n1 != 0:
    total += n1
sum = total / loopCounter
print("Your average is",sum)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM