Prime Number Checker (Code) in Python

← Back to Projects

Prime Number Checker in Python

About the project: Creating a Prime Number Checker project in Python. This will be a self-contained script that allows you to check if a number is prime.

This program will ask you to enter a number, and it will tell you if it's a prime number. It will run in a continuous loop so you can check multiple numbers without restarting the program.

How to use this Prime Number Checker:

  • Run the Python script.
  • When you run it, you can enter any number, and it will tell you whether it's a prime number or not. The program will continue to run until you type q to quit..


Project Level: Beginner

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# prime_number_checker.py

import math

def is_prime(num):
    """
    Checks if a given number is a prime number.

    A prime number is a natural number greater than 1 that has no positive
    divisors other than 1 and itself.

    Args:
        num (int): The number to check.

    Returns:
        bool: True if the number is prime, False otherwise.
    """
    # Prime numbers must be greater than 1
    if num <= 1:
        return False

    # Check for divisibility from 2 up to the square root of the number.
    # This is an optimization, as any divisor larger than the square root
    # would have a corresponding smaller divisor that would have already been found.
    for i in range(2, int(math.sqrt(num)) + 1):
        if num % i == 0:
            return False # Found a divisor, so it is not prime

    return True # No divisors were found, so it is prime

def main():
    """
    Main function to run the Prime Number Checker in a continuous loop.
    """
    print("--- Python Prime Number Checker ---")
    print("Enter a number to check if it's prime (or 'q' to quit).")

    while True:
        try:
            user_input = input("\nEnter a number: ").strip()

            # Check if the user wants to quit
            if user_input.lower() == 'q':
                print("Exiting Prime Number Checker. Goodbye!")
                break
            
            num = int(user_input)
            
            if is_prime(num):
                print(f"Result: {num} is a prime number.")
            else:
                print(f"Result: {num} is not a prime number.")

        except ValueError:
            print("Invalid input. Please enter a valid number.")

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()