Calculation of sum of digits

1
  

Write a program that receives an integer in the input, computes and prints the sum of the digits of this number in the output

     

Example:

     
>>>Digite um número inteiro: 123

>>>6
     

Tip: To separate the digits, remember: the "//" operator makes an entire division throwing away the rest, ie, that which is smaller than the divisor; The operator "%" returns only the rest of the whole division throwing out the result, ie everything that is greater than or equal to the divisor.

I did the code though, it has a repetition bug that I can not solve. Can anyone help me?

x=int(input("Digite um número para que seus digitos sejam somados: "))

soma=0
while (x>0):
    resto = (x // 10)%10
    resto_cont=(x%10)
    resto_cont2=(x//100)
    soma = resto + resto_cont + resto_cont2
print("valor é", soma)
    
asked by anonymous 09.12.2017 / 18:10

1 answer

0

Your program gets stuck inside while and never quits because x never changes.

In addition, if you have a while traversing the digits, you should have soma = soma + alguma_outra_coisa .

It is also worth noting that in while , you should be separating the last digit from the others. You are actually separating the last one, but in time to separate the others, you are doing it wrong and forgetting that you are within while .

Do this:

x = int(input("Digite um número para que seus dígitos sejam somados: "))

soma = 0
while x > 0:
    resto = x % 10
    x = x // 10
    soma = soma + resto

print("O valor é", soma)

With this entry:

123

This is the output:

O valor é 6

See here working on ideone.

    
09.12.2017 / 18:31