Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Computing average
#1
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)
Reply
#2
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')
Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  computing average in nested loops cap510 5 5,140 Sep-11-2020, 12:33 PM
Last Post: deanhystad
  Computing factorials Truman 6 4,074 Mar-14-2018, 06:38 AM
Last Post: DeaD_EyE
  computing the factorial of N foolsgold27 12 8,073 Aug-02-2017, 02:29 AM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020