By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
 464,332 Members | 1,209 Online
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,332 IT Pros & Developers. It's quick & easy.

# Printing the digits of an integer

 P: 3 I want to write a simple function that prints the digits of an integer in reverse. I think it could be done with the while loop, but I am not so sure. I have tried this, but it didn't work. Expand|Select|Wrap|Line Numbers def print_digits(n):     n = abs(n)     while n > 0:         n = n % 10         print n,   Jul 23 '08 #1
Share this Question
4 Replies

 100+ P: 314 In python % is the modulo operator... I'm not sure what you are trying here... Here's how to reverse the digits of an integer using list comprehension: Expand|Select|Wrap|Line Numbers >>> def print_digits(n): ...     new_n = [lett for lett in str(n)] ...     new_n.reverse() ...     print ''.join(new_n) ...      >>> print_digits(136) 631 >>>  Jul 23 '08 #2

 100+ P: 314 Oh wait.. now I see what you were trying to do... Expand|Select|Wrap|Line Numbers >>> def print_n(n): ...     while n > 0: ...         print n % 10, ...         n = n / 10 ...      >>> print_n(492) 2 9 4 >>>  Modulus 10 will give you the remainder but you want to integer divide by 10 each time to reduce the number another digit. Jul 23 '08 #3

 P: 3 Well, I am new to Python and I am reading this: http://openbookproject.net/thinkCSpy/ch06.xhtml#auto16 so the exercise is number 8 Expand|Select|Wrap|Line Numbers def print_digits(n):     """       >>> print_digits(13789)       9 8 7 3 1       >>> print_digits(39874613)       3 1 6 4 7 8 9 3       >>> print_digits(213141)       1 4 1 3 1 2     """   Hope this helps! Jul 23 '08 #4

 P: 3 Thanks for the quick reply. I can now sleep in peace. Jul 23 '08 #5

### Post your reply

Sign in to post your reply or Sign up for a free account.