Ray Harlequin Ray Harlequin - 1 year ago 89
Python Question

Program to add together a series of number

I am writing a program that will add together a series of
numbers a user inputs until the user enters a rogue value of 0. The
program will then display the total.

user_input = None
total_sum = 0
while user_input != 0:
user_input = input("Enter a number:")
total_sum = total_sum + user_input

# Sample output:
# Enter a number: 5
# Enter a number: 50
# Enter a number: 10
# Enter a number: 0
# The total sum of the numbers are 65
print("The total sum of the numbers are {}".format(total_sum))

The error that keeps coming up is :

total_sum = total_sum + user_input
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Answer Source

input returns a string, even if it's a string that contains a number (e.g., "5"). You need to explicitly convert it to an int:

user_input = int(input("Enter a number: "))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download