Python Program - Reverse a Number
here's a Python program that reverses a number:
# Get a number from the user num = int(input("Enter a number: ")) # Initialize a variable to store the reversed number reversed_num = 0 # Reverse the number using a while loop while num > 0: digit = num % 10 reversed_num = reversed_num * 10 + digit num = num // 10 # Print the reversed number print("Reversed number:", reversed_num)
In this program, we first prompt the user to enter a number using the input()
function, and convert the input to an integer using the int()
function.
We then initialize a variable reversed_num
to 0
, which will store the reversed number.
To reverse the number, we use a while loop that continues as long as the input number num
is greater than 0
. Inside the loop, we use the modulo operator %
to get the rightmost digit of num
, and add it to the reversed number reversed_num
multiplied by 10
. This has the effect of adding the rightmost digit to the left side of the reversed number, effectively reversing the order of the digits.
We then update the input number num
by dividing it by 10
using integer division //
, which removes the rightmost digit.
Once the loop has completed, we have reversed the entire number and stored it in reversed_num
. We can print this value using the print()
function.
Note that this program assumes that the input number is positive. If the number can be negative, you may need to handle negative signs separately.