Kacper
Kacper

Reputation: 79

Python not summing list correctly

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))

Upvotes: 4

Views: 440

Answers (3)

Celius Stingher
Celius Stingher

Reputation: 18377

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)))

Upvotes: 4

Sk.
Sk.

Reputation: 460

You missed the last value in more than one values.

numbers = []
More = True

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

print(sum(numbers))
print(len(numbers))
print(sum(numbers) / int(len(numbers)))

Upvotes: 2

Chris
Chris

Reputation: 4411

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.

Upvotes: 3

Related Questions