sum of number's caracters - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: sum of number's caracters (/thread-22067.html) |
sum of number's caracters - foli - Oct-28-2019 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 RE: sum of number's caracters - buran - Oct-28-2019 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)? RE: sum of number's caracters - perfringo - Oct-28-2019 '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. RE: sum of number's caracters - foli - Oct-28-2019 thanks for your respond i'm gonna think about it RE: sum of number's caracters - foli - Oct-28-2019 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 RE: sum of number's caracters - perfringo - Oct-28-2019 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) 21For 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 RE: sum of number's caracters - MckJohan - Nov-02-2019 you can use python built-in command. sum(map(int, str(x)))Point to study. builtin function map, str, and study about Python iterable. RE: sum of number's caracters - jefsummers - Nov-02-2019 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. |