Working with numerical data is an essential part of programming, and Python provides great tools to deal with it. In this tutorial, we will learn how to separate the digits of a three-digit number using Python. This might come in handy during data analysis, algorithms, and various other applications. Let’s jump into the steps.
Step 1: Accept Input
First, let’s accept a three-digit number from the user. We can use Python’s built-in function input()
for this purpose. The input will be stored in the variable number
.
1 |
number = input("Enter a 3-digit number: ") |
Step 2: Validate Input
Now, we need to ensure that the user has entered a valid three-digit number. We can use the isdigit()
function to check that the input is an integer and contains exactly 3 digits.
1 2 3 4 5 |
if number.isdigit() and len(number) == 3: number = int(number) else: print("Invalid input. Please enter a 3-digit number.") exit() |
Step 3: Separate Digits
Once we have a valid three-digit number, we can separate its digits using mathematical operations. We’ll use the floor division (//) and modulo (%) operators to achieve this.
1 2 3 |
first_digit = number // 100 second_digit = (number % 100) // 10 third_digit = number % 10 |
Step 4: Display Output
Finally, let’s display the separated digits to the user using the print()
function.
1 2 3 |
print("First digit:", first_digit) print("Second digit:", second_digit) print("Third digit:", third_digit) |
Full Code
Here’s the full code for separating the digits of a three-digit number in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
number = input("Enter a 3-digit number: ") if number.isdigit() and len(number) == 3: number = int(number) else: print("Invalid input. Please enter a 3-digit number.") exit() first_digit = number // 100 second_digit = (number % 100) // 10 third_digit = number % 10 print("First digit:", first_digit) print("Second digit:", second_digit) print("Third digit:", third_digit) |
Output
Enter a 3-digit number: 123 First digit: 1 Second digit: 2 Third digit: 3
Conclusion
In this tutorial, we learned how to separate the digits of a three-digit number in Python. This can be useful for various programming tasks and data analysis. By following these simple steps, you can easily implement this functionality in your Python projects.