Home > Software engineering >  Why won't list memorize previous inputs and sum them?
Why won't list memorize previous inputs and sum them?

Time:12-04

With each iteration the list only presents the last appended input and not the sum of the last input previous appended inputs.

def main_program():
    n = []
    n.append(int(input("insert:\n")))
    print(sum(n))
while True:
    main_program()
    if input("Add another number? (Y/N):\n") == "N":
        break

I'm trying to create a "snowball effect" for lack of a better description. I wanted the program to store each appended input and sum them all together.

CodePudding user response:

Define n just once.

def main_program():
    n.append(int(input("insert:\n")))
    print(sum(n))

n = []
while True:
    main_program()
    if input("Add another number? (Y/N):\n") == "N":
        break

Passing the list as parameter in the function main_program also works, since lists are call-by-reference.

  • Related