How to reverse a number in Python

Published on Aug. 22, 2023, 12:16 p.m.

There are different ways to reverse a number in Python. Here is an example program that uses a while loop to reverse a number:

num = int(input("Enter a number: "))
reversed_num = 0

while num > 0:
    remainder = num % 10
    reversed_num = (reversed_num * 10) + remainder
    num = num // 10

print("The reversed number is:", reversed_num)

In this program, we prompt the user to enter a number and convert the input to an integer using the int() function. Then we use a while loop to extract the rightmost digit of the number using the % operator, add it to the current reversed number multiplied by 10, and update the original number by removing the rightmost digit using the // operator. We repeat this process until the original number becomes 0. Finally, we print the reversed number to the console using the print() function.

Note that we use integer division // to divide the original number by 10 and remove the rightmost digit. This is necessary because regular division / would return a float, and we want to keep the result as an integer.

You can also convert the number to a string, reverse the string, and then convert the reversed string back to an integer using the int() function:

num = int(input("Enter a number: "))
reversed_num = int(str(num)[::-1])
print("The reversed number is:", reversed_num)

In this case, we use string slicing syntax to reverse the string obtained from the number using str(num). The syntax [::-1] means “reverse the string”. Then, we convert the reversed string back to an integer using the int() function, and print the result to the console.

Tags:

related content