Read an integer greater than 0 and return the sum between the numbers that compose it in Python

Asked

Viewed 129 times

-3

Could someone give me a light on how to make a code, in Python, that reads an integer number greater than 0 typed by the user and add the numbers that make up it?

Ex:

User type 129

Program returns 12

  • Transform the input into a string and then iterate over that string by converting each character to integer and summing them into an accumulator.

2 answers

0

I know it’s not the most readable answer, and I don’t recommend using it in production, but out of curiosity I’ll leave a one-Liner that does what was requested by the PO.

print('Soma dos dígitos:', sum(map(int, input('Informe um número inteiro: '))))

While not readable, this type of code shows how flexible the Python language is.

0

With the following code you perform the sum of the digits of the number:

n=int(input("Digita um número:"))

tot=0

while(n>0):
    dig=n%10
    tot=tot+dig
    n=n//10

print("A soma é:",tot)
  • 1

    Avoid giving full answers to this type of question. It is an academic execise that the user did not publish any resolution attempts. A complete answer is more disturbing than helpful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.