Python Program To Reverse a Number Using While Loop

Python Program To Reverse a Number Using While Loop

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:

  1. While loop

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.

Was this helpful?
YesNo

Related Articles:

Recent Articles:

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x