Extract and print digits in reverse order of a number in Python

Extracting digits in Python: Here, we are going to learn how to extract and print the digits in reverse order of a number in Python? By Anuj Singh Last updated : April 09, 2023

Here, we are going to use some mathematical base while programming. The problem is, when you ask a number from the user, the user would give input as multiple digit number (considering integer only). So it is easy to find the type of number but it’s not easy to find the number of digits in the number.

Printing digits of a number in reverse order

So, in the following problem, we are going to use the mathematical trick of:

  1. Subtracting the remainder after dividing it by 10 i.e. eliminating the last digit.
  2. Dividing an integer by 10 gives up an integer in computer programming (the above statement is only true when the variables are initialized as int only).

Example

Input: 12345

Output: 54321

Python program to extract and print digits of a number in reverse order

# input the number
num = int(input("Enter a number with multiple digit: "))
n=0

# Extracting and printing digits 
# in reverse order
while num>0:
    a = num%10
    num = num - a
    num = num/10
    print(int(a),end="")
    n = n + 1

Output

RUN 1:
Enter a number with multiple digit: 12345
54321

RUN 2:
Enter a number with multiple digit: 1008
8001

RUN 3:
Enter a number with multiple digit: 1
1

Explanation

Here, we are first using a loop with condition num>0, and the last digit of the number is taken out by using simple % operator after that, the remainder term is subtracted from the num. Then number num is reduced to its 1/10th so that the last digit can be truncated.

The cycle repeats and prints the reverse of the number num.

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.