Printing the digits of an integer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • verbtim
    New Member
    • Jul 2008
    • 3

    Printing the digits of an integer

    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.

    Code:
    def print_digits(n):
    	n = abs(n)
    	while n > 0:
    		n = n % 10
    		print n,
  • jlm699
    Contributor
    • Jul 2007
    • 314

    #2
    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:
    [code=python]>>> def print_digits(n) :
    ... new_n = [lett for lett in str(n)]
    ... new_n.reverse()
    ... print ''.join(new_n)
    ...
    >>> print_digits(13 6)
    631
    >>> [/code]

    Comment

    • jlm699
      Contributor
      • Jul 2007
      • 314

      #3
      Oh wait.. now I see what you were trying to do...
      [code=python]
      >>> def print_n(n):
      ... while n > 0:
      ... print n % 10,
      ... n = n / 10
      ...
      >>> print_n(492)
      2 9 4
      >>> [/code]
      Modulus 10 will give you the remainder but you want to integer divide by 10 each time to reduce the number another digit.

      Comment

      • verbtim
        New Member
        • Jul 2008
        • 3

        #4
        Well, I am new to Python and I am reading this:

        so the exercise is number 8
        Code:
        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!
        Last edited by verbtim; Jul 23 '08, 08:44 PM. Reason: another post

        Comment

        • verbtim
          New Member
          • Jul 2008
          • 3

          #5
          Thanks for the quick reply. I can now sleep in peace.

          Comment

          Working...