Help printing the integers of a longer number

Jussi Piitulainen jpiitula at
Thu Mar 28 18:03:49 CET 2013

khaosyt at writes:

> I want to print the individual numbers of a large number using
> division and modulus division.
> For example:
> Enter a positive integer: 54321
> 5
> 4
> 3
> 2
> 1

Those numbers are called the digits of the large number.

With divmod(54321, 10) you get both the number that is "left" after
removing the last digit, and the last digit:

>>> left, last = divmod(54321, 10)
>>> left
>>> last

Define a function, print_digits(num), that prints the digits of the
non-negative integer num. Zero turns out fine so let's allow zero:

def print_digits(num):
   left, last = divmod(num, 10)
   if left < 0: print the digits of left

How do you print the digits of left? With print_digits. Why does it
work? Because you only call print_digits again when left is closer to
zero than num.

It's called recursion.

More information about the Python-list mailing list