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.


Discover more from Python Mania

Subscribe to get the latest posts sent to your email.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Related Articles:

Recent Articles:

0
Would love your thoughts, please comment.x
()
x

Discover more from Python Mania

Subscribe now to keep reading and get access to the full archive.

Continue reading