Print works but function does not

I am a beginner trying to learn about functions right now, but I need some extra help;
I would like the user add to a list as many numbers as it wants until it inputs empty space. Then the function should print the total sum of them.
I think the while loop to add numbers works well because if I only print the list, the program works, but if I want to use the function to get the total, then it does not work.
Any ideas?

def addtogether (list):
    print(f'total is: {sum(list)}')

list = []
while True:
    n = input('Give a number, empty space stops : ')
    if n == (''):



Give a number, empty space stops : 3
Give a number, empty space stops : 3
Give a number, empty space stops : 
Traceback (most recent call last):
   line 11, in <module>
   line 2, in addtogether
    print(f'total is: {sum(list)}')
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Thanks beforehand and have a nice day :slight_smile:

  1. Avoid re-declaring built-in variables like list

  2. input() returns a string. You need to convert the output to integers before running numerical operations like sum, either by wrapping input into int() or by using map:

def addtogether(lst):
    print(f'total is: {sum(map(int, lst))}')

Although @vovavili has given you a very compact answer, I think it would be easier to follow if you took each number as it was input and converted it to an integer there in the loop. It would force you to decide what to do with strings typed in that couldn’t be converted, probably give the user some guidance, rather than the program dying mysteriously later.

1 Like

Thanks @vovavili for your time. Did you try to make it work with that code? I have but still can not make it work.

Thanks @jeff5, I will try that.

Did you get this:

ValueError: invalid literal for int() with base 10: ''


That’s because you added the final value, what the user types to finish, to the list of values to add up.

1 Like

@MRAB nope, that wasn’t the error.