How to Reverse a Number in Python

The following python program reverses a given multi-digit number. In this example, we simply print the digits in reverse order without removing redundant zeros. For example, if the input number is "1000", the reversed number displayed will be "0001" instead of "1".

number = int(input("Enter a number: "))
reverse_number = ''

while number > 0:
    last_digit = number % 10
    reverse_number = reverse_number + str(last_digit)
    number = number // 10

print("Reverse number is: ", reverse_number)

The above program uses the following logic to reverse the number,

  1. Extract the last digit using the modulus operator (Remainder of a number after dividing by 10)
  2. Add the last digit as the first digit in the reversed string
  3. Now remove the last digit from the original number dividing it with 10 (note the use of integer division operator //. The / operator if used will return a fraction!)
  4. Repeat from step 1 until the original number has no remaining digits

The following program uses a slightly different approach. In this example, we store the reversed number as an integer instead of a string. This ensures that when we reverse "1000", we get "1" instead of "0001". Note that before adding the last digit we multiply the previous number by 10 to increase its place value.

number = int(input("Enter a number: "))
reverse_number = 0

while number > 0:
    last_digit = number % 10
    reverse_number = reverse_number*10 + last_digit
    number = number // 10

print("Reverse number is: ", reverse_number)

The output of the program when run from console,

Enter a number: 9899
Reverse number is:  9989