Python Program to Check Prime Number

Prime Number Program in Python (Step by Step)

Are you looking for Prime Number Program in Python?

In this tutorial I will tell you step by step how to check Prime Number by Python. This is a Simple Python Program to Check Prime Number.

Here, we will explore the topic of prime numbers, explain the logic behind a prime number program in Python, and provide you with a sample program to check for prime numbers.

Prime Number Program in Python

A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself. Here I have shared two types of Prime Number Program in Python.

In simpler terms, a prime number is only divisible by 1 and itself. Some examples of prime numbers include 2, 3, 5, 7, 11, and so on. Prime numbers play a crucial role in various mathematical algorithms and are the foundation for many cryptographic methods.

Example 1:

Python Program to Check Prime Number

This Prime Number Program in Python will help to Check Prime Number. That is, when you run this program, you will input a number. This program will check and tell you whether it is a prime number or not?

				
					def is_prime(number):
    if number <= 1:
        return False
    if number <= 3:
        return True

    if number % 2 == 0 or number % 3 == 0:
        return False

    i = 5
    while i * i <= number:
        if number % i == 0 or number % (i + 2) == 0:
            return False
        i += 6

    return True

# Input from the user
num = int(input("Enter a number: "))

if is_prime(num):
    print(num, "is a prime number")
else:
    print(num, "is not a prime number")

				
			
Explanation of the above code

Below I have explained step by step how Prime Number Program in Python works. If you know basic Python then you can easily understand the following codes.

Step 1: Define the is_prime function:

				
					def is_prime(number):
				
			

This code defines a function named is_prime that takes an integer number as an argument. This function will be used to determine whether the given number is a prime number.

Step 2: Check if the number is less than or equal to 1:

				
					if number <= 1:
    return False

				
			

If the number is less than or equal to 1, it immediately returns False. Prime numbers are defined as integers greater than 1, so numbers less than or equal to 1 cannot be prime.

Step 3: Check if the number is 2 or 3:

				
					if number <= 3:
    return True

				
			

If the number is 2 or 3, it returns True because 2 and 3 are prime numbers.

Step 4: Check divisibility by 2 and 3:

				
					if number % 2 == 0 or number % 3 == 0:
    return False

				
			

It checks if the number is divisible by 2 or 3. If it is, it returns False because prime numbers greater than 3 should not be divisible by 2 or 3.

Step 5: Primality test using a loop:

				
					i = 5
while i * i <= number:

				
			

The code initializes a variable i to 5 and enters a while loop. It will continue executing the loop until i squared is greater than or equal to the number.

Step 6: Check for divisibility by i and i+2:

				
					if number % i == 0 or number % (i + 2) == 0:
    return False

				
			

Within the loop, it checks if the number is divisible by i or i + 2. If it is, it returns False. This is an optimization to skip checking divisibility by numbers that are multiples of 2 or 3, as they have already been handled in earlier steps.

Step 7: Increment i by 6:

				
					i += 6

				
			

The value of i is incremented by 6 in each iteration. This step is important because it alternates between checking for divisibility by numbers of the form 6k - 1 and 6k + 1

This is based on the fact that all prime numbers (greater than 3) can be represented in this form.

Step 8: Return True if no divisors are found:

If the loop completes without finding any divisors for the given number, the function returns True, indicating that the number is prime.

Step 9: Taking user input and displaying the result:

				
					num = int(input("Enter a number: "))

				
			

The program takes a user input as an integer and stores it in the variable num.

				
					if is_prime(num):
    print(num, "is a prime number")
else:
    print(num, "is not a prime number")

				
			

It calls the is_prime function with the user-provided number and prints whether the number is prime or not based on the function’s return value.

This is the first example of Prime Number Program in Python. If you struggle to understand please comment me.

Example 2:

Python Prime Number Program in Range

In this Python Prime Number Program you can easily find out which of the numbers in a range is a prime number. 

That is when you run this program you have to input start number and end number. Then this Prime Number Program in Python will tell you the prime numbers.

				
					def generate_primes_in_range(start, end):
    primes = []
    for num in range(start, end + 1):
        if num > 1:
            is_prime = True
            for i in range(2, int(num ** 0.5) + 1):
                if num % i == 0:
                    is_prime = False
                    break
            if is_prime:
                primes.append(num)
    return primes

start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))

if start < 2:
    start = 2  # Ensure we start with the first prime number, 2

prime_list = generate_primes_in_range(start, end)
print("Prime numbers in the range", start, "to", end, "are:", prime_list)

				
			
Explanation of the above code

Below I have explained step by step how Python Prime Number Program in Range works. 

Step 1: Define the generate_primes_in_range function:

				
					def generate_primes_in_range(start, end):

				
			

This function takes two arguments, start and end, which define the range of numbers within which we want to find prime numbers.

Step 2: Initialize an empty list for prime numbers:

				
					primes = []

				
			

The primes list will store the prime numbers found within the specified range.

Step 3: Iterate through numbers in the given range:

				
					for num in range(start, end + 1):

				
			

This for loop iterates through all numbers from start to end, inclusive.

Step 4: Check if the number is greater than 1:

				
					if num > 1:

				
			

This condition ensures that only numbers greater than 1 are considered because prime numbers, by definition, are greater than 1.

Step 5: Initialize a boolean variable to check for primality:

				
					is_prime = True

				
			

The is_prime variable is initially set to True, assuming that the current number is prime. We will check for divisibility to determine if it’s not prime.

Step 6: Check for divisibility by numbers up to the square root of num:

				
					for i in range(2, int(num ** 0.5) + 1):

				
			

This for loop iterates from 2 to the square root of num (rounded up to the nearest integer plus one). This loop checks for divisibility of num by all integers within that range.

Step 7: Check if num is divisible by i:

				
					if num % i == 0:

				
			

If num is divisible by i, it means num is not a prime number.

Step 8: Set is_prime to False and break the loop:

				
					is_prime = False
break

				
			

If num is found to be divisible by i, we set is_prime to False and break out of the loop since we’ve determined that num is not prime.

Step 9: If is_prime is True, add num to the list of primes:

				
					if is_prime:
    primes.append(num)

				
			

If is_prime is still True after checking divisibility by all numbers in the range, it means that num is prime, so we add it to the primes list.

Step 10: Return the list of prime numbers:

				
					return primes

				
			

After iterating through all numbers in the range, the function returns the list of prime numbers found.

Step 11: Take user input for the range and adjust the start if necessary:

				
					start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
if start < 2:
    start = 2

				
			

The program prompts the user to enter the start and end values for the range of numbers they want to check for prime numbers. If the start value is less than 2, it’s adjusted to 2 to ensure that we start with the first prime number, which is 2.

Step 12: Generate the list of prime numbers and print the result:

				
					prime_list = generate_primes_in_range(start, end)
print("Prime numbers in the range", start, "to", end, "are:", prime_list)

				
			

The program calls the generate_primes_in_range function with the adjusted range values, collects the list of prime numbers, and then prints the result, indicating which numbers within the specified range are prime.

Running the Prime Number Program in Python

To run this Prime Number Program, copy and paste it into a Python interpreter or save it to a .py file and execute it. The program will prompt you to enter a number, and it will then determine whether that number is prime or not.

Hopefully from this article you have learned how to create a Prime Number Program in Python. Let me know how you like this tutorial by commenting.

You can use this program to explore prime numbers or as a building block for more advanced mathematical and computational tasks.