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
Bytes IT Community
+ 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
  1. def print_digits(n):
  2.     n = abs(n)
  3.     while n > 0:
  4.         n = n % 10
  5.         print n,
  6.  
Jul 23 '08 #1
Share this Question
Share on Google+
4 Replies

jlm699
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
  1. >>> def print_digits(n):
  2. ...     new_n = [lett for lett in str(n)]
  3. ...     new_n.reverse()
  4. ...     print ''.join(new_n)
  5. ...     
  6. >>> print_digits(136)
  7. 631
  8. >>> 
Jul 23 '08 #2

jlm699
100+
P: 314
Oh wait.. now I see what you were trying to do...
Expand|Select|Wrap|Line Numbers
  1. >>> def print_n(n):
  2. ...     while n > 0:
  3. ...         print n % 10,
  4. ...         n = n / 10
  5. ...     
  6. >>> print_n(492)
  7. 2 9 4
  8. >>> 
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
  1. def print_digits(n):
  2.     """
  3.       >>> print_digits(13789)
  4.       9 8 7 3 1
  5.       >>> print_digits(39874613)
  6.       3 1 6 4 7 8 9 3
  7.       >>> print_digits(213141)
  8.       1 4 1 3 1 2
  9.     """
  10.  
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.