In this post, we will learn how to reverse a number in python with a detailed explanation and algorithm.

## Algorithm to Reverse a Number in Python

• Convert the given number into String Using the `str()` function.
• Reverse that string Using the slicing operator (`[::-1]`)
• Convert reversed string into an integer again.
• At last print the result.

From the above algorithm, we understood how to reverse a number in python but before writing a program few programming concepts you should know about:

### Source Code

``````num = 125 #input

num = str(num)  # convert int --> str
reversed_num = num[::-1]  # reverse a string

reversed_num = int(reversed_num)  # convert back str --> int
print(f"Reversed number is {reversed_num}") # result``````

### Output

we can also write the above program in just one line:

``````num = 45

reversed_num = int(str(num)[::-1])
print(f"Reversed number is {reversed_num}") ``````

Output

Let’s modify the above program and write it by taking input from the user

``````num = int(input('Enter a number: '))

reversed_num = int(str(num)[::-1])
print(f"Reversed number is {reversed_num}") ``````

Output

Now let’s write this program using a function.

## Reverse a Number in Python Using a Function

Before writing this program you should know about:

### Source Code

``````def reverse_num(num):
return int(str(num)[::-1])

my_num = int(input('Enter a number: ')) #user input

print(f'Given number: {my_num}')
print(f'Reversed number: {reverse_num(my_num)}')``````

### Output

There is one general approach to solving this problem let’s see it.

## Reverse a Number in Python Using a while loop

This is General Approach to reverse a number not only in python but in any programming language.

Before writing this program you should know about:

### Source Code

``````number = int(input('Enter a number: '))

res_num = 0

while number > 0:
reminder = number % 10
res_num = res_num*10 + reminder
number //= 10

print(f'Reversed number: {res_num}')``````

### Output

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.