Python Program to Reverse a Number
mediumwhile loopPython
Reversing digits with arithmetic, not string slicing, is what the practical exam usually asks for.
The question
Read a positive integer (it does not end in 0) and print the number with its digits reversed. Use a while loop — do not convert it to a string.
The code
program.py
n = int(input())
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n //= 10
print("Reversed =", rev)Input
71413
Output
Reversed = 31417
How it works
- 1rev starts at 0.
- 2Each loop: rev = rev * 10 + n % 10 shifts rev left by one digit and adds n's last digit.
- 3n //= 10 drops the digit that was just used.
- 4When n reaches 0, rev holds the reversed number.
Common mistakes
- Using str(n)[::-1] when the question says to use a loop.
- Forgetting rev * 10 — the digits get added instead of placed side by side.
Now solve a similar question yourself
A new Python question every time, checked instantly.
