K
khaosyt
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
For example:
Enter a positive integer: 54321
5
4
3
2
1
This looks familiar. Make the integer a string and use a for loop toI 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
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
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
Jussi said: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:
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)
def print_digits(num):
left, last = divmod(num, 10)
if left < 0: print the digits of left
print(last)
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.
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.