Python Program to Reverse Numbers

Python program to reverse number; Through this tutorial, i am going to show you how to reverse a number in Python.

And as well as, i write a python program to reverse a three, four, five and etc digit number in python.

How to reverse a number in Python

Use the following methods to reverse a number in python using while loop and function; as shown below:

  • Python Program to Reverse a Number using While loop
  • Python Program to Reverse a Number Using Recursion

Python Program to Reverse a Number using While loop

See the following python program to reverse of a number in python using while loop; as shown below:

 # Get input from the user
num = int(input("Please enter any number: "))
# Initiate value to null
test_num = 0
# iterate number using while loop
while(num>0):
  #Logic to reverse a number
  remainder = num % 10
  test_num = (test_num * 10) + remainder
  num = num//10
# print the result
print("The reverse number is : {}".format(test_num))

Output

Please enter any number:  123 
The reverse number is : 321 

Python Program to Reverse a Number using Using Recursion

Let’s see the python program to reverse a number using recursion function; as shown below:

# Get input from user
Num = int(input("Please Enter any Number: "))
Output = 0
def revNum(Num):
    global Output
    if(Num > 0):
        Reminder = Num %10
        Output = (Output *10) + Reminder
        revNum(Num //10)
    return Output
Output = revNum(Num)
print("Reverse of entered number is = %d" %Output)

Output

Please Enter any Number:  456 
Reverse of entered number is = 654 

Recommended Python Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.