Input=12345 output=54321
Program to write a reverse of numbers
n=int(input("Enter number :"))
rev=0
while(n>0):
dig = n%10
rev=rev*10+dig
n=n//10
print("The reverse of the number:" ,rev)
Can some explain why this print 54321
Let, n = 12345 , where 12345 is the given input.
rev = 0
Now in the first iteration of the while loop n > 0
dig = remainder of n divided by 10, So it is = 5
rev = rev(0) * 10 + dig(5) = 5
n = n // 10 = 1234
In the second iteration n = 1234 which is > 0
rev = 5
dig = remainder of n divided by 10, So it is = 4
rev = rev(5) * 10 + dig(4) = 54
n = n // 10 = 123
In the third iteration n = 123 which is > 0
rev = 54
dig = remainder of n divided by 10, So it is = 3
rev = rev(54) * 10 + dig(3) = 543
n = n // 10 = 12
In the fourth iteration n = 12 which is > 0
rev = 543
dig = remainder of n divided by 10, So it is = 2
rev = rev(543) * 10 + dig(2) = 5432
n = n // 10 = 1
In the fifth iteration n = 1 which is > 0
rev = 5432
dig = remainder of n divided by 10, So it is = 1
rev = rev(5432) * 10 + dig(1) = 54321
n = n // 10 = 0
Now in the sixth iteration of the while loop n = 0 so it is not greater than 0 so loop will break and you got rev = 54321
It's actualy pretty simple
1st iteration
2nd iteration
3rd iteration
...
However there is much easier way how to do this eg.
If your input is string so you just need to reverse it
input = "12345"
output = input[::-1]
If input is number (int, float) than you have to convert it to string
input = 12345
output = str(input)[::-1]
And convert back
int(output)
See other answer for great explanations. Here I add 2 simpler solutions to the original problem - how to reverse a number:
# For example, 12345:
num = input("Enter number: ")
# fastest and shortest:
rev = num[::-1]
# or (slower and longer)
rev = "".join(reversed(num))
print(f"The reverse of the number: {rev}")
# The reverse of the number: 54321