Python Practice › Loop Programs › Program 24
Reverse a number
Write a Python program to read a number and print its reverse.
Input
98760
Output
6789
Approach
- Build the reverse by moving each last digit to the end of a new number.
Solution
n = 98760reversed_n = 0while n > 0: reversed_n = reversed_n * 10 + n % 10 n //= 10print(reversed_n)Output
6789
Line by line
Line 4
Shift the result left by one place and add the next digit.
Note
The trailing 0 of 98760 becomes a leading zero, so the result prints as 6789.
Learn the concept
New to this topic? Read the lesson, then come back.