Python program to reverse a number :
In this tutorial, we will learn how to reverse a number in python. The program will take one integer number as input from the user, it will then reverse it and print it out.
For example, if the number is 154, the program will print 451 as the output.
Algorithm to solve this problem :
Following are the steps we will use to solve the problem :
1. Take the number as input from the user.
2. Take the rightmost digit of the number and add it to the first place of the resulting number.
3. Remove the last digit.
4. Similarly, remove the last digit continuously and keep adding it to the final number using a loop.
5. After the loop is completed, print out the final reverse number to the user.
Python program :
The python program to solve the problem is as below :
The commented numbers in the above program denote the step numbers below :
1. Ask the user to enter a number. Read it and store it in num variable.
2. Initialize one variable reverse_num to store the final reversed number. Initialize it to 0.
3. Run one while loop. Run the loop until the value of num is greater than 0.
4. Find the remainder of the variable num and store it in remainder variable.
5. Update the reverse_num. In this step, we are adding the remainder to its appropriate position.
6. Change the value of num to num//10.
7. Finally, print out the reverse number reverse_num.
If you got confused, let me explain it with an example. Suppose, we are finding the reverse number of 453. The steps will be as below :
After step 3, the while loop will exit and the reversed number will be printed as 354.
Sample Output :
In this tutorial, we have learned how to find the reverse of a number in python. Try to run the program and drop one comment below if you have any queries.
You might also like :
- Python program to find the first odd Abundant or excessive number
- Python 3 program to convert a decimal number to ternary (base 3)
- Python tutorial to calculate the sum of two string numbers
- Python program to find out numbers in a list divisible by two numbers
- Find out the multiplication of two numbers in Python
- How to remove item from a list in python