How to Create a Prime Number Checker in Python?

Estimated read time 2 min read

You can create a prime number checker in Python using a simple algorithm that checks if a number is divisible only by 1 and itself. Here’s an example code snippet:

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

# Example usage:
num = 23
if is_prime(num):
    print(num, "is a prime number.")
else:
    print(num, "is not a prime number.")

In this example, we define a is_prime function that takes a positive integer n as input and returns True if n is prime, and False otherwise.

We first check if n is less than or equal to 1, which is not a prime number. If n is greater than 1, we use a for loop to iterate over all possible divisors of n from 2 up to the square root of n. We use the int() and ** operators to calculate the square root of n.

If we find a divisor of n other than 1 or n itself, we immediately return False, indicating that n is not prime. If we have checked all possible divisors up to the square root of n without finding any factors, we can conclude that n is prime and return True.

Finally, we test the function by checking if the number 23 is prime using is_prime(23) and print a message accordingly. You can modify this code to check for prime numbers in a range or to input numbers from the user.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply