Python Forum
Computing average - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Computing average (/thread-12157.html)



Computing average - vestkok - Aug-12-2018

Hi guys, I have an exercise question from a book. I can't figure out where and how do I place error message if the first input from the user is 0.

P.S - To quit the loop, user must enter 0 according to the exercise question so cant use string to break it.

Thank you for any reply in helping out.

total = 0
counter = 0

while True:
    values = int(input("Enter the integer : "))
    if values == 0:
        break

    total += values
    counter += 1
    average = total / counter

print('The average of the numbers entered is %d' %average)



RE: Computing average - Axel_Erfurt - Aug-12-2018

total = 0
counter = 0
 
while True:
    values = int(input("Enter the integer : "))
    if values > 0:
        total += values
        counter += 1
    else: 
        if counter > 0:
            average = total / counter
            print('The average of the numbers entered is %d' %average)
        else:
            print('enter value > 0')



RE: Computing average - vestkok - Aug-12-2018

Hi Alex. Thank you so much for the guidance. Have revised the code as below to cover

total = 0
counter = 0

while True:
    try:
        values = int(input("Enter the integer : "))
        if values != 0:
            total += values
            counter += 1
        elif counter > 0:
            average = total / counter
            print('The average of the numbers entered is %.2f' %average)
        elif counter == 0:
            print('Invalid input as 0 is used to break loop')
        if values == 0:
            break
    except:
        print("Error. Kindly enter integer input only")
        break