Python Code to Check if a Number is Prime

A prime number is a natural number greater than 1 that has no divisors other than 1 and itself. For example, the numbers 2, 3, 5, 7, 11, and 13 are all prime numbers.

In this blog, I will provide a Python code to determine whether a given number is prime. The code checks if the number is divisible by any integer from 2 to the square root of the number. If no divisors are found within this range, the number is called a prime number; otherwise, it is not.

Here is the Python program that checks whether a given number is prime:

import sys

def is_prime(n):
    """
    this function checks if a given number is prime number. It divides the given number by all numbers between 2 and square root of the number to check if number can be divided by any number in the range.
    """
    if n <= 1:
        return False
    for i in range(2, int(pow(n, 1/2)) + 1):
        if n % i == 0:
            return False
    return True

def main():
    """
    prime number checker in Python
    """
    # provide a number as command-line argument
    args = sys.argv

    # check if user provided a value or not
    if len(args) < 2:
        print("please provide a number")
    else:
        num = int(args[1])
        if is_prime(num):
            print(f"{num} is a prime number")
        else:
            print(f"{num} is not a prime number")

if __name__ == "__main__":
    main()

Save the code as prime_checker.py (or any name you like). Run the script by providing a number as a command-line argument, as shown in the following example:

python prime_checker.py 11

Please let me know in the comments if you find any errors in the code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.