Reverse a Number in Python

Python Program to Reverse a Number

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

Some of the possible ways are given in the below list.

  • Convert number to string, Reverse string using slicing, and then Convert string back to number.
  • Use while loop to pop the last digit in iteration and create a new number with popped digits appended to it.

Example 1: Reverse Number using String slicing

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

try:
	n = int(input('Enter a number : '))
	reversed = int(str(n)[::-1])
	print(reversed)
except ValueError:
	print('Given input is not a number.')

Output

D:\>python example.py
Enter a number : 635178
871536

D:\>python example.py
Enter a number : asdf
Given input is not a number.

Example 2: Reverse Number using While Loop

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

try:
	n = int(input('Enter a number : '))
	reversed = 0
	
	while(n!=0):
		r=int(n%10)
		reversed = reversed*10 + r
		n=int(n/10)
		
	print(reversed)
except ValueError:
	print('Given input is not a number.')

Output

D:\>python example.py
Enter a number : 5236
6325

D:\>python example.py
Enter a number : 865474569
965474568

D:\>python example.py
Enter a number : 52dssa
Given input is not a number.

Summary

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