
- 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
Different Methods to find Prime Number in Python
First we need to know what a prime number is.
A prime number always a positive integer number and divisible by exactly 2 integers (1 and the number itself), 1 is not a prime number.
Now we shall discuss some methods to find Prime Number.
Method1
Using For loops
Example
def primemethod1(number): # Initialize a list my_primes = [] for pr in range(2, number): isPrime = True for i in range(2, pr): if pr % i == 0: isPrime = False if isPrime: my_primes.append(pr) print(my_primes) primemethod1(50)
Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Method2
For Loops with Break
Example
def primemethod2(number): # Initialize a list my_primes = [] for pr in range(2, number + 1): isPrime = True for num in range(2, pr): if pr % num == 0: isPrime = False break if isPrime: my_primes.append(pr) return(my_primes) print(primemethod2(50))
Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Method3
For Loop, Break, and Square Root
Example
def primemethod3(number): # Initialize a list primes = [] for pr in range(2, number): isPrime = True for num in range(2, int(pr ** 0.5) + 1): if pr % num == 0: isPrime = False break if (isPrime): print("Prime number: ",pr) primemethod3(50)
Output
Prime number: 2 Prime number: 3 Prime number: 5 Prime number: 7 Prime number: 11 Prime number: 13 Prime number: 17 Prime number: 19 Prime number: 23 Prime number: 29 Prime number: 31 Prime number: 37 Prime number: 41 Prime number: 43 Prime number: 47
- Related Articles
- Different Methods to find Prime Number in Python Program
- Analysis of Different Methods to find Prime Number in Python
- Different Methods to find Prime Number in Java
- Analysis of Different Methods to find Prime Number in Python program
- Different Methods to find Prime Numbers in C#
- Java methods to check for prime and find the next prime
- Python Program to Find if a Number is Prime or Not Prime Using Recursion
- Program to find number of different subsequences GCDs in Python
- Python Program to Check Prime Number
- What are different data conversion methods in Python?
- Program to find number of different substrings of a string for different queries in Python
- 5 Different methods to find length of a string in C++?
- I am the smallest number, having four different prime factors. Can you find me?
- Python Program for Find largest prime factor of a number
- Program to find number of different integers in a string using Python

Advertisements