Reversing numbers is a common task in Python programming. In this tutorial, we will walk you through the steps to create a Python program that reverses a given number. We will explain the process step by step, making it easy for beginners to understand.

## How to Reverse the Digits of a Number in Python

The reverse operation requires a number to swap the first and last digits, the second and second-to-last digits, and so on. For example, if you have the number 12345, reversing it would result in 54321. You may need to reverse a nondecimal number in various applications, such as checking for palindromes or solving mathematical problems.

### Prerequisites

Before you begin, ensure that you have Python installed on your system. You can download and install Python or run it via any of the online Python compilers.

Must Read: 10 Best Python IDEs for Coding

### 1. While Loop to Reverse a Given Number in Python

The reversing logic in Python is quite simple. You need to extract the digits from the given number and then reverse their order. To make this work, you should try the following six steps:

- Initialize a variable to store the reversed number (initially set to 0).
- Use a loop to extract the final digit of the input number.
- Add the extracted digit to the reversed number, taking into account its position (e.g., if the final digit is 5, add it as the unit place, if it’s 4, add it as the tens place, and so on).
- Remove the final digit from the input number.
- Repeat steps 2-4 until all digits are extracted and added to the reversed number.
- The reversed number is now stored in the variable, and you can print it.

Let’s implement this logic in Python code.

#### While Loop Program to Reverse the Digits of a Number in Python

```
# Function to reverse a given number
def rev_num_while_loop(num):
rev_no = 0
while num > 0:
# Extract the final digit
last_digit = num % 10
# Add the final digit to the reversed number
rev_no = (rev_no * 10) + last_digit
# Remove the final digit from the number
num = num // 10
return rev_no
# User to enter te input
num = int(input("Input a number to reverse: "))
# Call the reverse_number function and store the result
result = rev_num_while_loop(num)
# Display the reversed number
print("The number after the reverse operation:", result)
```

Also Read: 7 Unique Ways to Reverse a List in Python

#### Explanation

- We define a method
`rev_num_while_loop(num)`

that takes an integer`num`

as its parameter. This function will return the reversed number. - We initialize the
`rev_no`

variable to 0, which will store the reversed number. - We enter a while loop that continues as long as the input number (
`num`

) is greater than 0. - Inside the loop, we use the modulo operator
`%`

to extract the final digit of the number, and we store it in the variable`last_digit`

. - We add them
`last_digit`

to the`rev_no`

, taking its position into account by multiplying the`rev_no`

by 10 before adding the`last_digit`

. This step ensures that the digits are placed in the correct order when building the reversed number. - We remove the final digit from the input number by using the floor division operator
`//`

. - The loop continues until all digits have been extracted and added to the reversed number.
- After the loop, we return the
`rev_no`

. - We call the
`input()`

function for user input, convert it to an integer using`int()`

, and store it in the`num`

variable. - We call the
`rev_num_while_loop()`

function with`num`

as the argument and save the output in the`result`

variable. - Finally, we print the reversed number.

#### Example Output

Let’s see an example of running the program:

```
Input a number to reverse: 37159
The number after the reverse operation: 95173
```

Our Pick: String Splitting in Python

### 2. String Slicing Program to Reverse a Number in Python

String slicing in Python is a unique way to reverse the digits of a number. In this method, we’ll convert the number to a string, reverse the string, and then convert it back to an integer. Here’s how you can do it:

```
# Function using string slicing
def rev_num_string_slicing(num):
# Convert the number to a string
num_str = str(num)
# Reverse the string using slicing
reversed_str = num_str[::-1]
# Convert the reversed string back to an integer
rev_no = int(reversed_str)
return rev_no
# User to enter the input
num = int(input("Input a number to reverse: "))
# Call the reverse_number function and store the result
result = rev_num_string_slicing(num)
# Display the reversed number
print("The number after the reverse operation:", result)
```

Checkout: Python Remove Last Element from a List

#### Explanation

- We define a method
`rev_num_string_slicing(num)`

that takes an integer`num`

as its parameter. This function will return the reversed number. - Inside the function, we first convert the integer
`num`

to a string using`str()`

, and we store it in the variable`num_str`

. - We use string slicing with
`[::-1]`

to reverse the string. This slicing syntax means to start at the end, move backward by one character at a time, and include all characters. This effectively reverses the string. - After reversing the string, we convert it back to an integer using
`int()`

and store it in the variable`rev_no`

. - The function returns the
`rev_no`

. - We call the input() function to ask the user to enter a value. Convert it to an integer using
`int()`

, and store it in the`num`

variable. - We call the
`rev_num_string_slicing()`

function with`num`

as the argument and save the result in the`result`

variable. - Finally, we print the reversed number.

#### Example Output

Let’s see an example of running the program:

```
Input a number to reverse: 37159
The number after the reverse operation: 95173
```

In this Python program, we’ve reversed a number using string slicing. The key idea is to convert the number to a string, reverse the string using slicing, and then convert it back to an integer. This method is a bit more concise than the previous one, and it’s a good alternative if you prefer string manipulation for reversing numbers.

Also Try: Python Get Last Element in a List

### 3. Recursion to Reverse the Digits of a Number in Python

In order to reverse the digits of a number, we can make use of a recursive function in Python. In this approach, we will define a recursive method that separates the final digit from the rest of the number. It then reverses the number by recursively calling itself. Here’s how you can do it:

```
# Function using recursion
def rev_num_recursion(num):
# Base case: If the number has only one digit
if num < 10:
return num
# Extract the final digit
last_digit = num % 10
# Recursively reverse the remaining part of the number
rev_no = rev_num_recursion(num // 10)
# Construct the reversed number
return last_digit * 10 ** (len(str(num)) - 1) + rev_no
# User to enter the input
num = int(input("Input a number to reverse: "))
# Call the reverse_number function and store the result
result = rev_num_recursion(num)
# Display the reversed number
print("The number after the reverse operation:", result)
```

#### Explanation

- We define a recursive function
`reverse_number(num)`

that takes an integer`num`

as its parameter. This function will return the reversed number. - In the base case, we check if the number
`num`

is less than 10, which means it has only one digit. In this case, we simply return the number because there’s no need to reverse it further. - If the number has more than one digit, we extract the final digit by taking the modulo
`%`

with 10 and store it in the variable`last_digit`

. - We recursively call the
`reverse_number`

function with the remaining part of the number by using integer division`//`

to remove the final digit. - In the recursive calls, this process continues until we reach the base case.
- When we return from the recursion, we construct the reversed number by multiplying the
`last_digit`

by 10, to the power of the number of digits minus 1. This places`last_digit`

at the correct position within the reversed number. - The function returns the
`rev_no`

. - After that, call
`input()`

to ask for user input. Convert the value to an integer using int(), and store it in the`num`

variable. - We call the
`reverse_number()`

function with`num`

as the argument and store the output in the`result`

variable. - Finally, we print the reversed number.

Recommended: Python Append to a Dictionary

#### Example Output

Let’s see an example of running the program:

```
Input a number to reverse: 37159
The number after the reverse operation: 95173
```

In this Python program, we’ve reversed a number using a recursive function. The recursive approach separates the final digit from the remaining part of the number and reverses it by recursively calling the function. This method is a more difficult but nice way to reverse numbers and is useful for understanding recursion in Python.

**Pros and Cons**

The following table compares the above three ways to reverse the digits of a number in Python:

Method | Pros | Cons |
---|---|---|

While loop | Simple and straightforward to implement. | Can be inefficient for large numbers. |

String slicing | Efficient for all numbers. | Requires converting the number to a string. |

Recursive function | Elegant and concise implementation. | Can be inefficient for large numbers due to the overhead of calling the function recursively. |

In Python, you need to decide which is the most suitable method for you to reverse a number as per your specific needs. If speed is your concern, then go for string slicing. However, if you want a simple clean code, then use the while loop. The recursive function is the least efficient, but it is good when you want to wrap it with fewer lines of code.

Don’t Miss: Python Sorting a Dictionary

## Conclusion

In this tutorial, you learned how to create a Python program to reverse a number. The reverse operation takes the digits out of a number from right to left and builds a new number in reverse sequence. Our example programs used a `while`

loop, string slicing, and recursion to reverse the digits of a number in Python. You can use the code of these sample programs in your tasks as you find necessary.