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
number % 10gives the last digit, andnumber //= 10removes it.reversed_number * 10 + last_digitmoves the digits already collected one place to the left and adds the new digit at the end. The values go 5, 54, 543, 5432, 54321.- The program reverses
abs(n)and adds the minus sign back at the end, so -123 becomes -321. - Zeros at the end disappear: 1200 reversed is 21, not 0021, because a whole number cannot start with zeros.
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.