Home > Mobile >  While Loop - Inaccurate total count of negative integers
While Loop - Inaccurate total count of negative integers

Time:04-14

I'm supposed to write a code that exits when 0 is entered. Then find the sum of numbers entered and the amount of positive, negative integers. I can't figure out how to make the total count of negative integers right. What could be wrong?

num = 0
total = 0
pos = 0
neg = 0
L = []

while(True):
    num = int(input('Enter the number(If you enter 0, the program quits) : '))
    if num == 0:
        break
    L.append(num)
    total  = num
    num  = 1
    if num >= 0:
        pos  = 1
    else:
        neg  = 1
print('Entered numbers:', L)
print('Total : %d, Positive numbers : %d, Negative numbers : %d' % (total, pos, neg))

CodePudding user response:

Put the if-else above the num = 1 line or else when you calculate the positive or negative numbers, num has been changed to another value. The code should be like this:

L.append(num)
total  = num
if num >= 0:
    pos  = 1
else:
    neg  = 1
num  = 1
  • Related