简体   繁体   中英

How do I add the user inputs together?

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.

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(number):
    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(number))

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM