-4

Consider the following input prompt. I want to output the sum of digits that are inputted.

Example:

two_digit_number = input("Type a two digit number: ") 39
# program should print 12 (3 + 9) on the next line

If I input 39, I want to output 12 (3 + 9). How do I do this?

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33

6 Answers6

1

You can use sum(), transforming each digit to an integer:

num = input("Enter a two digit number: ")
print(sum(int(digit) for digit in num))
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
0

maybe like this:

numbers = list(input("Enter number: "))
print(sum(list(map(int, numbers))))
  1. Read digits with input as a whole number of string type
  2. split them with list() in characters in a list
  3. use map() to convert type to int in a list
  4. with sum() you're done.. just print()

Beware of invalid entries! "hundred" or "1 234 567"

msy
  • 9
  • 3
-1

This is one of the many ways for it.

    value = 39 # it is your input
    
    value_string = str(value)
    
    total = 0
    for digit in value_string:
        total += int(digit)
    
    print(total)

new version according to need mentioned in comment:


    value = 39
    
    value_string = str(value)
    
    total = 0
    digit_list = []
    for digit in value_string:
        total += int(digit)
        digit_list.append(digit)
    
    print(" + ".join(digit_list))
    
    print(total)
hazalciplak
  • 476
  • 1
  • 5
  • 10
  • no. its not working. input 39 . sum = 12 . its ok. but it showing direct 12 . i want to show 3+9 first. then showing result. – MAMUNUR RAHMAN Feb 01 '22 at 15:52
  • It wasn't mentioned on the question. If you want like that, you can save every digit in variables or all in a list in the for loop, then you can print them before printing the sum at the end. – hazalciplak Feb 01 '22 at 17:02
-1

you can achieve that like this:

a = input("Type a two digit number: ")
b = list(a)
print(int(b[0])+int(b[1]))
adev
  • 21
  • 3
  • A good answer will always include an explanation why this would solve the issue, so that the OP and any future readers can learn from it. – Tyler2P Feb 01 '22 at 19:57
-1
n = (int(input("Enter the two digit number\n")))
n = str(n)
p = int(n[0])+int(n[1])
print(p)
Ritesh.
  • 1
  • 1
-2

You can do that as follows:

two_digit_number = input("Type a two digit number: ") 
digits = two_digit_number.split("+")
print("sum = ", int(digits[0])+int(digits[1]))

Explanation:

  1. first read the input (ex: 1+1)
  2. then use split() to separate the input statement into the strings of the input digits only
  3. then use int() to cast the digit from string to int
E_net4
  • 27,810
  • 13
  • 101
  • 139