Python Program To Check Whether a Number Is Prime or Not

1. Introduction

A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. In other words, it has exactly two distinct natural number divisors: 1 and itself. Checking whether a given number is prime or not is a fundamental problem in number theory and has applications in various areas of mathematics and computer science. This blog post will guide you through creating a Python program to check if a given number is prime.

2. Program Steps

1. Prompt the user to enter a number.

2. Check if the number is less than 2, in which case it's not prime.

3. For numbers 2 and greater, check if the number is divisible by any number from 2 to the square root of the given number.

4. If the number is found to be divisible, it's not prime.

5. If the number is not divisible by any number in the range, it's prime.

3. Code Program

# Step 1: Get the number from the user
num = int(input("Enter a number: "))

# Function to check if the number is prime
def is_prime(n):
    # Step 2: Numbers less than 2 are not prime
    if n < 2:
        return False
    # Step 3 & 4: Check for factors from 2 to the square root of n
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

# Check if the entered number is prime and display the result
if is_prime(num):
    print(f"{num} is a prime number.")
else:
    print(f"{num} is not a prime number.")

Output:

Enter a number: 29
29 is a prime number.

Explanation:

1. The user is prompted to enter a number, which is read as an integer.

2. The is_prime function checks if the number is prime. It first verifies if the number is less than 2, in which case it immediately returns False as numbers less than 2 are not prime by definition.

3. For numbers 2 and above, the function checks for divisibility by any number from 2 up to the square root of the given number (n). This range is sufficient because if n has a factor larger than its square root, then it must also have a factor smaller than the square root, and we would have found it by this point in the loop.

4. If the function finds a divisor in this range, it returns False, indicating that n is not prime. If no divisors are found, the function returns True, indicating that n is prime.

5. The main part of the program uses the is_prime function to check the entered number and then prints out whether the number is prime or not based on the function's return value.


Comments