Reverse Digits of a Number in Python
Reverse the digits of an integer using a loop.
BeginnerLoop ProgramsExample 5 of 25
reverse-digits-of-a-number.py
Run in browser1# Program to reverse digits of a number23num = int(input("Enter an integer: "))45rev = 06temp = abs(num)78while temp > 0:9 digit = temp % 1010 rev = rev * 10 + digit11 temp //= 101213if num < 0:14 rev = -rev1516print("Reversed number is", rev)
Output
Enter an integer: 1234 Reversed number is 4321
What's going on
We build the reversed number by shifting previous digits left (×10) and adding the current last digit each iteration.