Python program: Reverse a number
Reverse the digits of a number: 1234 becomes 4321.
The code
n = 1234 rev, x = 0, n while x > 0: rev = rev * 10 + x % 10 x //= 10 print(rev) print(int(str(n)[::-1])) # the string shortcut
Output
4321 4321
How it works
Each pass takes the last digit of x and appends it to rev. The shortcut reverses the text with a slice.
Python features used
Learn the ideas behind it in the free lesson Loops.