Why does my loop end after the input is entered?

Issue

The homework question is: "Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total
and average of the input values (not counting zeros). Your program ends with the
input 0. Display the average as a floating-point number."

positive = 0
negative = 0
total = 0
count = 0

number = eval(input("Enter an integer, the input ends if it is 0:"))
while number != 0:
    total += number
    count += 1
    if number > 0:
        positive += 1
    elif number < 0:
        negative += 1
    else:
        break

average = total/count
print("The number of positives is", positive)
print("The number of negatives is", negative)
print("The total is", total)
print("The average is", average)

After a number is inputted, the program does not output anything else.

Solution

Write a program that reads an unspecified number of integers

That implies that you have to repeatedly take number inputs from the users, but using input() would only really input a single number at a time.

So you should input your number inside the while-loop, example:

while True:
    number = int(input("Enter an integer, the input ends if it is 0:"))
    total += number
    count += 1
    if number > 0:
        positive += 1
    elif number < 0:
        negative += 1
    elif number == 0:
        break

Answered By – Manik

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published