Reverse a Number - Python Program


Python Programs to Reverse a Number

In this tutorial, we will learn different ways to reverse a number in Python.

The first approach is to convert number to string, reverse the string using slicing, and then convert string back to number.

The second approach is to use while loop to pop the last digit in the loop, and create a new number with popped digits appended to it.

Examples

1. Reverse Number using String slicing in Python

In this example, we convert given number to string using str() and then reverse it using string slicing. The reversed string is converted back to int.

If the given input is not a number, we shall print a message to the user.

Python Program

n = 123456
reversed = int(str(n)[::-1])
print(reversed)

Output

654321

2. Reverse Number using While Loop in Python

In this program we shall use while loop to iterate over the digits of the number by popping them one by one using modulo operator. Popped digits are appended to form a new number which would be our reversed number.

Python Program

n = 123456
reversed = 0

while(n!=0):
    r=int(n%10)
    reversed = reversed*10 + r
    n=int(n/10)
    
print(reversed)

Output

654321

Summary

In this tutorial of Python Examples, we learned how to reverse a number using while loop and string slicing.