Editor

Python Program to Reverse a Number

Beginner · Numbers

Reversing a number means writing its digits in the opposite order, so 12345 becomes 54321. This program builds the reversed number digit by digit using arithmetic, without turning it into a string.

Program

reverse_a_number.py
num = 12345 # or: num = int(input("Enter a number: "))
reversed_num = 0
n = num
while n > 0:
digit = n % 10 # take the last digit
reversed_num = reversed_num * 10 + digit # add it to the end
n = n // 10 # remove the last digit
print("Original number:", num)
print("Reversed number:", reversed_num)
Output
Original number: 12345
Reversed number: 54321

How it works

  1. n % 10 takes the last digit of n.
  2. reversed_num * 10 + digit shifts the reversed number one place to the left and adds the digit at the end.
  3. n // 10 drops the last digit, and the loop continues until n is 0.
  4. Zeros at the end of the original disappear, so 1200 reverses to 21, because a number cannot start with zeros.

Another way to write it

Using string slicing

Using string slicing
num = 12345
reversed_num = int(str(num)[::-1])
print("Original number:", num)
print("Reversed number:", reversed_num)
Output
Original number: 12345
Reversed number: 54321

str(num) turns the number into text, [::-1] reads it backwards, and int() turns it back into a number.

Try it yourself

Use the reversed number to check whether 12321 is a palindrome, a number that reads the same both ways.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises