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

So let’s start with the 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:

  1. Python String
  2. Python Slicing operator

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

Reversed number is 521

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

Reversed number is 54

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

Enter a number: 451
Reversed number is 154

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:

  1. How to take user-input
  2. Python String
  3. Python Slicing
  4. Python Functions

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

Enter a number: 1234
Given number: 1234
Reversed number: 4321

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:

  1. How to take user-input
  2. while-loop
  3. Python Operators

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

Enter a number: 123
Reversed number: 321
Author

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.

Write A Comment