- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Python program to check if a number is Prime or not

A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. Any whole number which is greater than 1 and has only two factors that is 1 and the number itself, is called a prime number

Let’s say the following is our input −

7

The output should be as follows −

Prime Number

## Check if a number is Prime or not

Let us check if a number if a Prime number or not using the for loop −

### Example

# Number to be checked for prime n = 5 # Check if the number is greater than 1 if n > 1: for i in range(2, int(n/2)+1): if (n % i) == 0: print(num, "is not a prime number") break else: print(n, "is a prime number") # If the number is less than 1, its also not a prime number. else: print(n, "is not a prime number")

### Output

5 is a prime number

## Check if a number is Prime or not using sqrt()

Let us check if a number if a Prime number or not using the sqrt() method −

### Example

from math import sqrt # Number to be checked for prime n = 9 flag = 0 if(n > 1): for k in range(2, int(sqrt(n)) + 1): if (n % k == 0): flag = 1 break if (flag == 0): print(n," is a Prime Number!") else: print(n," is Not a Prime Number!") else: print(n," is Not a Prime Number!")

### Output

9 is Not a Prime Number!

- Related Questions & Answers
- C# Program to check if a number is prime or not
- PHP program to check if a number is prime or not
- Bash program to check if the Number is a Prime or not
- Check if a number is Primorial Prime or not in Python
- Write a C# program to check if a number is prime or not
- Python Program to Find if a Number is Prime or Not Prime Using Recursion
- Check if a number is Quartan Prime or not in C++
- Check if a number is Primorial Prime or not in C++
- C++ Program to Check Whether a Number is Prime or Not
- C Program to Check Whether a Number is Prime or not?
- Java Program to Check Whether a Number is Prime or Not
- Check if a number is a Pythagorean Prime or not in C++
- 8085 program to determine if the number is prime or not
- How to check whether a number is prime or not using Python?
- Program to check whether every rotation of a number is prime or not in Python

Advertisements