Python Forum

Full Version: sum of number's caracters
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi i have problems solving this homework :
write a program in python that inputs a number and prints the summation of its characters till the sum is under 10 :
for example:
input: 5896
output:28
10
1
i really need sb to solve it for me
thanks so much Heart
Welcome to the forum. Unfortunately it does not work like this. We are glad to help, but we are not going to do your homework for you.
Please, post your code in python tags. full traceaback (if any) - in error tags. Ask specific question(s)?
'sb to solve it for me' not gonna work. Put some effort into it and write some code and if problem encountered ask for help.
thanks for your respond
i'm gonna think about it
its my code but its not working fine
indentation is okay

a=int(input())
c=0
d=0
while a>10 :
    for i in str(a):
        b=str(i)
    
        c+=int(b)
        d=c
    
            
    if c<10 :
        print(c)
        a=c

    else:

         print(c)
         a=c
         c-=d
         if a==10:
             print(1)
             break
To give you some ideas: there are simple ways to sum digits in number.

For strings ('give me character converted into int for every character in string and sum'):

>>> s = '123456'
>>> sum(int(char) for char in s)
21
For integer 'add reminder to total until there is no floor':

>>> num = 123456
>>> total = 0
>>> while num:
...     num, reminder = divmod(num, 10)
...     total += reminder
... 
>>> total
21
you can use python built-in command.

 sum(map(int, str(x)))
Point to study. builtin function map, str, and study about Python iterable.
Assuming (I know that is bad) that you are early in your training and are just familiar with strings and numbers, your approach was to work with the digits as numbers. While possible, would it not be easier to work with the digits as characters, converting just to add? Then take the total and convert back to a string. When the string has a length of 1 you are done (a whole number less than 10 is one character long). Similar to Perfringo's approach, but keeping to the simplest structures
input_string = "135246"
while len(input_string) > 1 :
    total = 0
    for c in input_string :
        total += int(c)
Print the total, convert the total back to be input_string, and you are done.