Reversing a number means writing its digits in the opposite order. For example, 1234 becomes 4321. In this lesson you will reverse a number with a while loop, with string slicing and with recursion, and see what happens to numbers that end in zero.
Run the code in our online Python compiler. The compiler does not take keyboard input, so the examples use fixed values.
Method 1: using a while loop
The idea is to take the last digit of the number again and again, and add it to the end of the reversed number.
def reverse_number(n):
reverse = 0
while n > 0:
digit = n % 10
reverse = reverse * 10 + digit
n = n // 10
return reverse
print(reverse_number(1234))
print(reverse_number(1200))
print(reverse_number(5))Output:
4321
21
5How it works
n % 10 gives the last digit, and n // 10 removes the last digit. Here is the loop for n = 1234:
Step | digit | reverse | n after the step |
|---|---|---|---|
1 | 4 | 4 | 123 |
2 | 3 | 43 | 12 |
3 | 2 | 432 | 1 |
4 | 1 | 4321 | 0 |
In each step, reverse * 10 makes room for a new digit at the end, and + digit puts the digit there. The loop stops when n becomes 0.
Method 2: using string slicing
Convert the number to a string, reverse it with [::-1], and convert it back.
n = 1234
print(int(str(n)[::-1]))Output:
4321Method 3: using recursion
def reverse_recursive(n, reverse=0):
if n == 0:
return reverse
return reverse_recursive(n // 10, reverse * 10 + n % 10)
print(reverse_recursive(1234))Output:
4321Numbers that end in zero
When you reverse a number as a number, the leading zeros disappear. 1200 becomes 21, not 0021. If you want to keep the zeros, treat the number as a string:
print(int(str(1200)[::-1]))
print(str(1200)[::-1])Output:
21
0021Which method should you use?
Method | Best for |
|---|---|
while loop | Exams, and understanding the logic |
String slicing | The shortest code |
Recursion | Learning how recursion works |
Take the number from the user (on your computer)
n = int(input('Enter a number: '))
print('Reversed number:', reverse_number(n))Our online compiler does not support input() yet, so use a fixed value there.
Common mistakes
- Starting reverse at 1. It must start at 0.
- Forgetting n = n // 10. The loop then never ends.
- Using / instead of //. Normal division gives a decimal number, and the loop does not work as intended.
- Negative numbers. The loop above returns 0 for them. Reverse the absolute value with abs(n), and add the sign back if you need it.
Practice questions
- Reverse the number 98765.
- Check whether a number is a palindrome using the reverse program.
- Reverse a negative number such as -123.
- Print the digits of a number in reverse order, one per line.
FAQs
How do you reverse a number in Python without converting it to a string?
Use a while loop with n % 10 and n // 10, as in Method 1.
What is the reverse of 100?
As a number it is 1, because the zeros come first and disappear. As a string it is ‘001’.
How do I reverse a string in Python?
Use slicing: text[::-1].
