0

I got my code to check for how many digits that i type in my raw input

num = int(raw_input("Enter, "))


import math
   
digits = int(math.log10(num))+1
   
print digits

example 1587898 then it prints 7 digits

I need my code to calculate the digits i type in my raw input until it reaches a single digit
for example i type 4569841. then it will add those numbers 4+5+6+9+8+4+1
it will print 37. it will continue to add 3 + 7 and it will print 10. It continues to add again 1+0 and prints 1 and it stops there because 1 is a single digit.

I can't seem to figure out and what code i need to add the digits together.
I think i am suppose to use a while loop like this

while digits >1:

and it will continue to add the number as long as digit is greater then 1 but i am not sure what code i need to sum up the numbers i type.

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by pyTony
0

There are many possible algorithms. If you can build a list with the digits, the built-in function sum() could be a solution

>>> mylist = [4, 7, 5, 8]
>>> sum(mylist)
24

Edited by Gribouillis: n/a

0

use number, digit= divmod(number, 10) . Continuation condition should be while sum(digits) > 9:

>>> number = 123456
>>> while number:
	number, digit = divmod(number, 10)
	print digit

	
6
5
4
3
2
1

Edited by pyTony: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.