Python programs / Numbers / Reverse a number

Python Program to Reverse a Number

Beginner Numbers

Reverses the digits of a number, so 1234 becomes 4321, by taking them off the end with % 10 and // 10.

Reversing a number turns 1234 into 4321. This program does it with arithmetic rather than text: it takes the digits off the end of the number with % 10 and // 10, and builds a new number from them in the opposite order. The same loop is the heart of the palindrome number check.

Program

def reverse_number(number):
    """The digits of number in reverse order, as a number."""
    reversed_number = 0
    while number > 0:
        digit = number % 10
        reversed_number = reversed_number * 10 + digit
        number //= 10
    return reversed_number


print("Reverse of 1234:", reverse_number(1234))
print("Reverse of 1200:", reverse_number(1200))

Open in the editor Download reverse_number.py

Output

Reverse of 1234: 4321
Reverse of 1200: 21

How it works

  1. reversed_number starts at 0 and is built up one digit at a time.
  2. The loop runs until every digit of number has been used.
  3. number % 10 is the last digit: 4 for 1234.
  4. Multiplying by 10 moves the digits so far one place to the left, which makes room for the new digit at the end: 43 becomes 430, and adding 2 gives 432.
  5. //= 10 removes the last digit from number, so the next round takes the one before it.
  6. When number reaches 0, all its digits are in reversed_number, which the function returns.
  7. The program reverses 1234, then 1200, which gives 21: a number can't start with zeros, so 0021 is 21.

For 1234:

number digit reversed_number
1234 4 0 ร— 10 + 4 = 4
123 3 4 ร— 10 + 3 = 43
12 2 43 ร— 10 + 2 = 432
1 1 432 ร— 10 + 1 = 4321

Then number is 0 and the loop stops.

Other ways to write it

With str() and slicing

As text, [::-1] reverses a string (strings). int() turns the result back into a number and drops any zeros at the front.

def reverse_number(number):
    return int(str(number)[::-1])

print(reverse_number(1234), reverse_number(1200))

Try it yourself

  • Reverse 7, 10 and 987654321.
  • Make it work for a negative number, so -345 gives -543: reverse abs(number), then put the minus sign back.
  • Reverse 120, then reverse the answer: you get 12, not 120, as the zero was lost on the way.
  • Add a number to its reverse: 1234 + 4321 is 5555.

More numbers programs

Share this program