简体   繁体   中英

How to print sum of digits for a Python integer?

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?

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))

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

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"

If you want to sum the digits of two digits int eger you can do something like this:

number: str = input()
print(int(number[0]) + int(number[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)

you can achieve that like this:

a = input("Type a two digit number: ")
b = list(a)
print(int(b[0])+int(b[1]))
n = (int(input("Enter the two digit number\n")))
n = str(n)
p = int(n[0])+int(n[1])
print(p)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM