Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python not summing list correctly

Tags:

python

list

sum

Python is not summing all items in the list. What did I do wrong?

I'm trying to make a program that calculates the average of inputed numbers and it seems like the len() is working correctly but sum() is only summing some numbers.

numbers = []
More = True

while More:
    xInp = input('Number: ')
    yInp = input('Again?(y/n) ')
    if yInp == 'y':
        numbers.append(int(xInp))
    elif yInp == 'n':
        break

print(sum(numbers))
print(len(numbers) + 1)
print(sum(numbers) / int(len(numbers) + 1))
like image 259
Kacper Avatar asked Dec 31 '22 11:12

Kacper


2 Answers

The problem is the order, you are exiting the program without considering the last value being input. Altering the order a bit will help you solve the issue. Furthermore be careful with apostrophes and doble apostrophes, I've edited that in the answer too, as it will return a SyntaxError otherwise:

numbers = []

while True:
    xInp = input('Number: ')
    numbers.append(int(xInp))
    yInp = input('Again?(y/n) ')
    if yInp == 'y':
        pass
    elif yInp == 'n':
        break

print(sum(numbers))
print(len(numbers))
print(sum(numbers) / int(len(numbers)))
like image 69
Celius Stingher Avatar answered Jan 03 '23 02:01

Celius Stingher


Your code will only add the most recently-entered number to the array if the user selects y at the next prompt. Once they enter n, the last number entered is not appended to the list.

You need to append the number right after it has been entered, then check if the user wants to add more.

numbers = []

while True: # No need for a variable here
    xInp = input("Number: ")
    numbers.append(int(xInp))
    yInp = input("Again? (y/n): ")
    if yInp == "y":
       pass
    elif yInp == "n":
        break

print(sum(numbers))

By convention, variables start with lowercase letters. Uppercase first letters are for class definitions (not instances). I had originally changed More to more, but as mentioned in the comments, it is not even necessary, so I replaced it with while True.

like image 34
Chris Avatar answered Jan 03 '23 01:01

Chris