Hi!
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?
Input
def addtogether (list):
print(f'total is: {sum(list)}')
list = []
while True:
n = input('Give a number, empty space stops : ')
list.append(n)
if n == (''):
break
addtogether(list)
Output:
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>
addtogether(list)
line 2, in addtogether
print(f'total is: {sum(list)}')
TypeError: unsupported operand type(s) for +: 'int' and 'str'
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.