Help printing the integers of a longer number

Jussi Piitulainen jpiitula at ling.helsinki.fi
Thu Mar 28 13:11:03 EDT 2013


Jussi Piitulainen writes:

> khaosyt at gmail.com 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
> 5432
> >>> last
> 1
> 
> 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
>    print(last)

Blush. That should be:

    ...
    if left > 0: ...
    ...

(Or just "if left" because left will eventually be 0, positive numbers
are true values, and 0 is a false value.)

Sorry about that.

> 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