Python Practice › Basic Programs › Program 24

Reverse a number

EasyBasic Programs · 24 of 40

Write a Python program to reverse the digits of a number.

Advertisement
Input
12345
Output
54321

Approach

  1. Take the last digit with % 10 and remove it with // 10.
  2. Build the reversed number digit by digit.

Solution 1: arithmetic

Python
n = 12345reversed_n = 0while n > 0:    digit = n % 10    reversed_n = reversed_n * 10 + digit    n //= 10print(reversed_n)
Output
54321

Line by line

Line 4

n % 10 is the last digit (5 first).

Line 5

Shifting the result one place left (* 10) and adding the digit appends it.

Line 6

//= 10 removes the last digit; the loop ends when n reaches 0.

Solution 2: string slicing

Python
n = 12345print(int(str(n)[::-1]))
Output
54321

Line by line

Line 2

Convert to a string, reverse it with [::-1] and convert back to int.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs