Home > OS >  How do I add the user inputs together?
How do I add the user inputs together?

Time:11-18

number = 0

def sumDigits(number):
    while True:
        number = int(input("Please enter a number (enter 0 to exit):"))
        if number == 0:
            sum = number   number
            print("The sum is",sum)
            break

print(sumDigits(number))

After 0 is entered, the program outputs "The sum is 0" and then on the next line it outputs "None" I'm not sure what's happening out why the "None" is there.

I need the program to add all the user inputs together.

CodePudding user response:

You can make a list, and append all the values the user enters to that list. Then use the built-in sum function (to add all the values in the list), and return the result.

number = 0
lst = []
def sumDigits():
    while True:
        number = int(input("Please enter a number (enter 0 to exit):"))
        lst.append(number)
        if number == 0:
            add = sum(lst)
            return f"The sum is {add}"
            break
            

print(sumDigits())

Your program wouldn't work previously because you are just adding the current numbers the player entered which was always 0, and you weren't returning any values, which is why you got a None.

Another side-note: Do not name the variable sum, because it is a built-in function as I said above.

Also, there is no need for the number argument in your function as well because it is not being used.

CodePudding user response:

Use another variable to hold the total, and add to it each time through the loop.

def sumDigits(number):
    total = 0
    while True:
        number = int(input("Please enter a number (enter 0 to exit):"))
        if number == 0:
            print("The sum is",total)
            break
        total  = number

CodePudding user response:

There are multiple mistakes. First of them is if you do print(sumDigits(number)), then you print the return value of the sumDigits function. You do this by using the "return" keyword. Second is the line sum = number number. Problem number one here is that sum is a built-in function and that means you must not use it as a variable identifier. Problem number two is that in this case sum equals the same number times two, not two different numbers added.

What you want to do is something like following:

number = 0

def sumDigits(number):
    while True:
        new_number = int(input("Please enter a number (enter 0 to exit): "))
        if not new_number == 0:
            number  = new_number
        else: break

print(sumDigits(number))
  • Related