How To Find Digits Of A Number In Python

In this tutorial, you’ll learn how to find the digits of a number in Python. Being able to extract the digits of a number is a common task, especially when you’re trying to develop solutions that involve working with numbers.

To achieve this, we will discuss two methods: the traditional method of dividing and modulo operations, and the one-liner method using list comprehension and string conversion.

Method 1: Traditional Method Using Divide and Modulo Operations

Below are the steps to find the digits of a number using the traditional method in Python:

Step 1: Get user input for our number.

Step 2: Initialize an empty list to store the digits.

Step 3: Extract the digits using a while loop.

In this step, we use the modulo operator % to get the rightmost digit of the number and store it in the variable digit. We then use the // operator for integer division and update the value of number until it becomes zero.

Step 4: Reverse the digits list since we have stored them in reverse order.

Step 5: Print the digits list.

Method 2: One-Liner Method Using List Comprehension and String Conversion

In this method, we will use list comprehension along with string conversion:

Step 1: Get user input for our number.

In this step, we do not convert the input into an integer, as we will be using the string directly.

Step 2: Find the digits using list comprehension and string conversion.

This will create a list of integers (digits) from the characters of the input string number.

Step 3: Print the digits list.

Full Code

Output

Enter a number: 12345
Digits of the number using Method 1 are: [1, 2, 3, 4, 5]
Enter a number: 12345
Digits of the number using Method 2 are: [1, 2, 3, 4, 5]

Conclusion

Now you know how to find the digits of a number using two different methods in Python. The first method employs the traditional technique of dividing and modulo operations, whereas the second method offers a more concise one-liner using list comprehension and string conversion. You can use either method, depending on your project requirements and readability preferences.