Python Program to Reverse a Number

It has now been seven years since I am exploring my ways in the world of New Age technology. In all these years, what is my favourite thing in the whole world? I would say my keyboard! If it’s a war, I got my code as the skill and my keyboard as the weapon. When I was a kid, I wondered what it would feel like to be a hacker. I kept feeding my curiosity in the bits and pieces. I was getting introduced with new things everyday and over time. All this passion has made me targeted towards my main objective, that is, to learn everything which is out there about computer. For now, I have got a good grip over Python, JavaScript, C and C++. I think the main reason for my motivation is that I strongly believe, if you keep your mind clear and devote yourself to pure learning, there will come a time when your own reality will get surrounded by your self-made uniqueness.
In this tutorial, we will learn how to reverse a number in python.
Explanation ✏
- First of all, let's take input from the user for eg 1326
- Then we need to use a while loop and set the value of n > 0, which means the while loop run until the value of n is not equal to 0.
- Then r = n % 10 means if the number is 1326 then it first prints the last number 6 then 2, 3, and at last 1.
- After that rev = (rev * 10) +r means at first the value is 6, then 62, 623, and 6231 (please set the value of rev = 0 at first)
- Then finally n = n // 10 it means at first the value of n is 132 ( it removes the last digit then 13, 1, and finally 0.
- When the value of n is 0 then the loop ended. And, the final output is 6231
Code 👩💻
def reverse(n):
rev = 0
while(n>0):
r = n % 10
rev = (rev * 10) + r
n = n // 10
return rev
num = int(input("Enter a number: "))
print(reverse(num))
STEPS 👇
Let n = 1326
#1
r = 1326 % 10 #ans: 6
rev = (0*10) + 6 #ans: 6
n = 1326 // 10 #ans: 132
#2
r = 132 % 10 #ans: 2
rev = (6*10) + 2 #ans: 62
n = 132 // 10 #ans: 13
#3
r = 13 % 10 #ans: 3
rev = (62*10) + 3 #ans: 623
n = 13 // 10 #ans: 1
#4
r = 1 % 10 #ans: 1
rev = (623*10) + 1 #ans: 6231
n = 13 // 10 #ans: 0




