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:
- User has to enter a value.
- Using a loop, we will get each digit of the number by taking modulus to the numb
- Divide the number with 10 to remove last digit.
- 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
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)
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:-