Python Practice › Loop Programs › Program 24

Reverse a number

EasyLoop Programs · 24 of 90

Write a Python program to read a number and print its reverse.

Advertisement
Input
98760
Output
6789

Approach

  1. Build the reverse by moving each last digit to the end of a new number.

Solution

Python
n = 98760reversed_n = 0while n > 0:    reversed_n = reversed_n * 10 + n % 10    n //= 10print(reversed_n)
Output
6789

Line by line

Line 4

Shift the result left by one place and add the next digit.

Note

The trailing 0 of 98760 becomes a leading zero, so the result prints as 6789.

Advertisement

Learn the concept

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

More loop programs

← All 90 Loop Programs