Reverse Digits of a Number

Reverse the digits of an integer using a loop.

BeginnerTopic: Loop Programs
Back

Python Reverse Digits of a Number Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# Program to reverse digits of a number

num = int(input("Enter an integer: "))

rev = 0
temp = abs(num)

while temp > 0:
    digit = temp % 10
    rev = rev * 10 + digit
    temp //= 10

if num < 0:
    rev = -rev

print("Reversed number is", rev)
Output
Enter an integer: 1234
Reversed number is 4321

Understanding Reverse Digits of a Number

We build the reversed number by shifting previous digits left (×10) and adding the current last digit each iteration.

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents