In this code we are going to discuss how you can reverse a given number using a while loop in Python:
Simple code:
num = int(input("Enter a number: "))
reverse_num = 0
while num != 0:
digit = num % 10
reverse_num = reverse_num * 10 + digit
num = num // 10
print("The reversed number is:", reverse_num)
Output:
Enter a number: 258
The reversed number is: 852
Code with comments:
# get the input number from the user
num = int(input("Enter a number: "))
# initialize the reverse_num variable to 0
reverse_num = 0
# continue looping until num becomes 0
while num != 0:
# get the last digit of the number
digit = num % 10
# add the digit to the reverse_num variable
reverse_num = reverse_num * 10 + digit
# remove the last digit from the number
num = num // 10
# print the reversed number
print("The reversed number is:", reverse_num)
In the above code, we first get the input number from the user using the input() function and convert it to an integer using the int() function.
We then initialize the reverse_num variable to 0.
We use a while loop to get the last digit of the number using the modulo operator %.
Then we add it to the reverse_num variable and remove the last digit from the number using integer division //.
We repeat this process until the number becomes 0. Finally, we print the reversed number using the print() function.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.