
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to check whether a number is prime or not using Python?
Principle used in following solution to this problem is to divide given number with all from 3 its square root, a number's square root is largest possible factor beyond which it is not necessary to check if it is divisible by any other number to decide that it is prime number.
The function returns false for all numbers divisible by 2 and less than 2. For others return value of all) function will be false if it is divisible by any number upto its square root and true if it is not divisible by any number
Example
def is_prime(a): if a < 2: return False elif a!=2 and a % 2 == 0: return False else: return all (a % i for i in range(3, int(a**0.5)+1) ) num=int(input('enter a number')) if is_prime(num)==True: print ("{} is a prime number".format(num)) else: print ("{} is not a prime number".format(num))
Output
Sample run of above program −
enter a number24 24 is not a prime number enter a number47 47 is a prime number
- Related Articles
- How to check whether a number is a prime number or not?
- Check whether N is a Dihedral Prime Number or not in Python
- 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
- How To Check Whether a Number is Pointer Prime Number or Not in Java?
- Check whether the given number is Wagstaff prime or not in Python
- Program to check whether every rotation of a number is prime or not in Python
- Write a Golang program to check whether a given number is prime number or not
- Python program to check if a number is Prime or not
- How to Check Whether a String is Palindrome or Not using Python?
- Check if a number is Primorial Prime or not in Python
- Python Program to Find if a Number is Prime or Not Prime Using Recursion
- How to Check Whether a Number is Krishnamurthy Number or Not in Java?
- How To Check Whether a Number is Strontio Number or Not in Java?

Advertisements