Python Program to Reverse a Numbers

Python Program to Reverse a Numbers

The objective of this Python post, you will see various Python programs that cover the following:

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

1: Python Program to Reverse a Number using While loop

 # 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 

2: Python Program to Reverse a Number using Using Recursion

# 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 

Leave a Reply

Your email address will not be published. Required fields are marked *