Python program to reverse a number
Contents
This program reverses a number entered by user and then it print it on the output screen.Example .If the user enters the number 456,the program will return the output as 654.Here the program using modulus(%) operator to obtain the digits of a number.The original number returned from right to left in the output screen.
Program to reverse a number:
def reverse(n):
d=0
rev=0
while(n>0):
d=n%10
n=int(n/10)
rev=rev*10+d
return rev
x=int(input("Enter the number:"))
r=reverse(x)
print("Reverse of the Number:",r)
Output

Explanation
The input function used to get the keyboard input from user and int is used to store the user input as numeric in the variable x.Next the function reverse gets called with the input of x and the while loop gets executed until the number greater than zero.
First iteration: n>0 => 43872>0 (true condition)
d = n%10
=> 43872%10
=> 2
n = n/10
=> 43872/10
=> 4387
rev = rev*10+d
=> 0*10+2
=> 2
Second iteration n>0=> 4387>0 (true condition)
d = 4387%10 => 7
n = 4387/10 => 438
rev = 2*10+7 => 27
Third iteration n>0 => 438>0 (true conditon)
d = 438%10 => 8
n = 438/10 => 43
rev = 27*10+8 => 278
Fourth iteration n>0 => 43>0 (true condition)
d = 43%10 => 3
n = 43/10 => 4
rev = 278*10+3 = 2783
Fifth iteration n>0 => 4>0 (true condition)
d = 4%10 => 4
n = 4/10 = 0
rev = 2783*10+4 =>27834
Sixth iteration n>0 => 0>0 (false condition)