How To Check If A Digit Is Present In A Number Python

In this tutorial, we will learn how to check if a digit is present in a given number using Python. This problem can be solved using various approaches, and in this tutorial, we will look at two of them, i.e., by converting the number to a string and iterating, and by dividing the number and checking the remainder.

Step 1: Converting the Number to String

The first approach is to convert the given number to a string, and then check if the digit to be verified is present in the string. We can use the str() function to convert a number to a string and check for the presence of the digit using the in keyword.

Step 2: Using Division and Modulus

Another approach is to divide the given number and check the modulus (remainder) with the given digit. We can use a while loop to divide the number until it becomes 0 and check if the remaining matches the given digit.

Step 3: Comparing the Two Methods

Let’s compare both methods by running them on a sample input.

Using method 1: Yes
Using method 2: Yes

You can see that both methods correctly identify if the digit is present in the given number.

Full Code

Here’s the full code for both methods, along with the output.

Is the digit 3 present in the number 12345 ? Yes
Is the digit 3 present in the number 12345 ? Yes
Using method 1: Yes
Using method 2: Yes

Conclusion

In this tutorial, we have learned how to check if a digit is present in a number using Python. We covered two different approaches, i.e., converting the number to a string and iterating, dividing the number, and checking the remainder.

Both methods work effectively and can be used according to your preference or the specific requirements of your project.