Python Program to reverse digits of a given number

In this tutorial, we are going to learn how to reverse a given number in Python by making the reverse of digits. So let’s get started.

Reverse the Number in Python

To reverse a given number we need to follow some steps.

Steps to follow:

  1.  User has to enter a value.
  2. Using a loop, we will get each digit of the number by taking modulus to the numb
  3. Divide the number with 10 to remove last digit.
  4.  Print the reverse number.

In this program, we create a function named reverse. The reverse function takes a number as an argument and returns the reversed number.

def reverse(number): 
  y=0 
  while(number>=1):
   z = number % 10
   y = 10 * y + z
   number = number / 10
   number = int(number)
  return y

Explanation :

The last digit of the number can be obtained by using the modulus operator. In the above program, we used while loop to get each digit. The last digit is added to variable y in above program.

Divide the number with 10 to remove the last digit in the given number. This loop terminates when the value of the number is 0 and returns variable y to the main program.




Final code: Reverse digits of a number in Python

def reverse(number):
  y=0
  while(number>=1):
   z = number % 10
   y = 10 * y + z
   number = number / 10
   number = int(number)
  return y
Number=int(input("Enter a number: "))
reverse_number=reverse(Number)
print("Reverse of the number",Number," is ",reverse_number)

output:

Enter a number: 567
Reverse of the number 567 is 765

So Guy’s, I hope you really enjoy this tutorial and feel free to leave a comment if you have any doubt.

you may also learn:-

Python program to find Armstrong Numbers between an interval

Python program to sort elements in ascending order using bubble sort


Leave a Reply

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