Python Program to reverse a number using loop

Here is a simple program to find the reverse of an entered number. Please note that this program works for only positive integers.

Source Code:

x = input("Please Enter a number to reverse: ")
reverse = 0

while(x):
    reverse = reverse * 10
    reverse = reverse + x % 10
    x = x/10

print(reverse)

Output:

Please Enter a number to reverse: 12345
54321

Explaination of the logic

In the above given program, we get the reversed number in the reverse variable (initialized to 0) after completing the while loop.
we add the last digit of the number with reverse variable each time in the loop then we get rid of the last digit by diving it with 10.
Let’s see the value of reverse variable after each iteration for an example input, say 12345
(1)
(2) 5
(3) 54
(4) 543
(5) 5432
(6) 54321

Leave a Reply

Your email address will not be published.