In this tutorial, you will learn to write a Python Program To Reverse a Number Using While Loop.
To understand this program you should have an understanding of the following topics:
Python Program To Reverse a Number Using While Loop
num = int(input("Enter a number: "))
reverse = 0
while num > 0:
digit = num % 10
reverse = reverse * 10 + digit
num = num // 10
print("The reversed number is:", reverse)
Output
Enter a number: 12345nThe reversed number is: 54321
In this program, we first prompt the user to input a number.
We then declare a variable reverse and initialize it to 0.
We then enter a while loop, which continues until num becomes 0.
In each iteration of the loop, we find the rightmost digit of num by using the modulus operator %.
We add this digit to reverse by multiplying reverse by 10 and adding the digit.
This “shifts” the digits of reverse one place to the left and adds the new digit on the right.
We then remove the rightmost digit from num by using integer division //.
This is equivalent to “shifting” the digits of num one place to the right and removing the rightmost digit.
We repeat this process until num becomes 0.
Once the loop finishes, we print out the final value of reverse, which is the reversed number.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.