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))
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)))
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With