-2

I'm trying to create a program that takes a number and sums it But for some reason the code wont work

number = input("please enter a four digit number: ")
final = sum(number)
print(final)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

I've attempted to convert it into a integer and string but it keeps saying that each of them is irritable

What am I doing wrong?

3 Answers3

1

input returns a string. So you have to convert each char to an integer before you can sum them

>>> number = '1234'
>>> final = sum(map(int, number))
>>> print(final)
10
Sunitha
  • 11,777
  • 2
  • 20
  • 23
0

Try using this.

def sumNumber():
    number = input("please enter a four digit number: ")
    return sum(int(x) for x in number)

print(sumNumber())

#   Examples:
#   22222 returns 10
#   12345 returns 15

This function converts the string input into a list of integers, then returns the sum of the array using sum().

TruBlu
  • 441
  • 1
  • 4
  • 15
0

OR:

number = input("please enter a four digit number: ")
final = sum(int(i) for i in number)
print(final)

Ex output:

please enter a four digit number:  1234
10
U13-Forward
  • 69,221
  • 14
  • 89
  • 114