PythonMastery

Reverse a number in Python

Reverse the digits of a number with % and // in a while loop, keep the minus sign for negative numbers, and do the same with string slicing.

Reversing 12345 gives 54321. The program takes the digits off the end of the number one by one and builds the new number from them.

The program

python
n = int(input("Enter a number: "))

number = abs(n)
reversed_number = 0
while number > 0:
    last_digit = number % 10
    reversed_number = reversed_number * 10 + last_digit
    number //= 10

if n < 0:
    reversed_number = -reversed_number

print(f"Reversed: {reversed_number}")

Typed in this example: 12345. Press Run to type your own.

output
Enter a number: 12345
Reversed: 54321

How it works

Another way: string slicing

python
for n in [12345, -123, 1200]:
    text = str(abs(n))[::-1]
    reversed_number = int(text)
    if n < 0:
        reversed_number = -reversed_number
    print(n, "->", reversed_number)
output
12345 -> 54321
-123 -> -321
1200 -> 21

[::-1] is a slice with a step of -1. It reads the string from the end to the start. The reverse a string page explains it in more detail. Without abs(), str(-123)[::-1] would be "321-", and int() would raise a ValueError.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Operators & Expressions