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.

Recommended Answers

All 2 Replies

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

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.