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.
1 |
number = int(input("Enter a number: ")) |
Step 2: Initialize an empty list to store the digits.
1 |
digits = [] |
Step 3: Extract the digits using a while loop.
1 2 3 4 |
while number > 0: digit = number % 10 digits.append(digit) number = number // 10 |
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.
1 |
digits.reverse() |
Step 5: Print the digits list.
1 |
print("Digits of the number are:", digits) |
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.
1 |
number = input("Enter a 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.
1 |
digits = [int(d) for d in number] |
This will create a list of integers (digits) from the characters of the input string number
.
Step 3: Print the digits list.
1 |
print("Digits of the number are:", digits) |
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Method 1: Traditional Method number = int(input("Enter a number: ")) digits = [] while number > 0: digit = number % 10 digits.append(digit) number = number // 10 digits.reverse() print("Digits of the number using Method 1 are:", digits) # Method 2: One-Liner Method number = input("Enter a number: ") digits = [int(d) for d in number] print("Digits of the number using Method 2 are:", digits) |
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.