Python Program to Check Prime Number

You are Here:

What is Prime Number?

A positive integer that is divisible only by itself and 1.

Tips: It is recommended to use our online Prime Numbers calculator for better understanding.

Examples

The following table provides few examples of prime numbers.

NumberDivisorResult
131, 13Prime Number
151, 3, 5, 15Not a Prime Number
471, 47Prime Number

Using for loop

In the following example, we will check whether the given number (7) is a Prime number or not using for loop.

Example

Python Compiler
num = 7 count = 0 for i in range(1, num+1): if(num % i == 0): count += 1 if(count == 2): print("%d is a prime number" % num) else: print("%d is a NOT prime number" % num)

Output

7 is a prime number

Using while loop

In the following example, we will check whether the given number (7) is a Prime number or not using while loop.

Example

Python Compiler
num = 7 i = 1 count = 0 while(num >= i): if(num % i == 0): count += 1 i += 1 if(count == 2): print("%d is a prime number" % num) else: print("%d is a NOT prime number" % num)

Output

7 is a prime number

Prime Numbers between the Given Range

In the following example, we will find all the Prime numbers between 1 and 20.

Example

Python Compiler
start = 1; end = 20; print("Prime numbers between 1 and 20:") for start in range(start, end+1): count = 0; for i in range(1, start+1): if(start % i == 0): count += 1 if(count == 2): print(start, end=" ")

Output

Prime numbers between 1 and 20: 2 3 5 7 11 13 17 19

Check Whether the Given Number is Prime or Composite

In the following example, we will check whether the given number is a Prime number or Composite number.

Example

Python Compiler
num = int(input("Enter a (int) number: ")); count = 0; for i in range(1, num+1): if(num % i == 0): count += 1; if(count > 2): print("%d is a composite number" % num) else: print("%d is a prime number" % num)

Output

Enter a (int) number: 24 24 is a composite number

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on Python with examples for quick and easy learning.

We are working to cover every Single Concept in Python.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author