Reverse a Number in Python Without using Loop

We will develop a program to reverse a number in python without using loop. To reverse a number we need to extract the last digit of the number and add that number into a temporary variable with some calculation, then remove the last digit of the number. Do these processes until the number becomes zero.

Example of reverse number:-
Number: 12489
Reverse Number: 98421

Reverse a Number Without using Loop in Python

We will take integer numbers while declaring the variables. We read a number and reverse a number using slice operations. We will convert the integer number to string using str() and then, calculate the reverse of a number using the slicing operation. Finally, the result will be displayed on the screen.

Syntax of slicing operation:- str(num) [::-1]

# Python program to reverse a number without using loop

# take inputs
num = 12345
# calculate reverse of number
reverse = int(str(num)[::-1])

# calling function and display result
print('The reverse number is =', reverse)

Output:-

The reverse number is = 54321

Reverse a Number in Python Without using Loop

In the previous program, inputs are hardcoded in the program but in this program, input will be provided by the user.

# Python program to reverse a number without using loop

# take inputs
num = int(input('Enter the number: '))

# calculate reverse of number
reverse = int(str(num)[::-1])

# calling function and display result
print('The reverse number is =', reverse)

Output for the input values test-case-1:-

Enter the number: 16574
The reverse number is = 47561

Output for the input values test-case-2:-

Enter the number: 130163
The reverse number is = 361031

Output for the input values test-case-3:-

Enter the number: 14650931
The reverse number is = 13905641

Python Program to Reverse a Number Without using Loop

We can also use the recursion technique to reverse a number in Python. A technique of defining the method/function that contains a call to itself is called recursion. The recursive function/method allows us to divide the complex problem into identical single simple cases that can handle easily. This is also a well-known computer programming technique: divide and conquer.

# Python program to reverse a number without using loop

reverse, base = 0, 1
def findReverse(num):
   global reverse  #function definition
   global base   #function definition
   if(num > 0):
      findReverse((int)(num/10))
      reverse += (num % 10) * base
      base *= 10
   return reverse

# take inputs
num = int(input('Enter the number: '))

# calling function and display result
print('The reverse number is =', findReverse(num))

Output:-

Enter the number: 49846
The reverse number is = 64894

Leave a Comment

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