For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
How do you check if a number is prime in Python—without using guesswork?It’s a common problem for beginners, but once you know the logic, it’s easier than it sounds.
A prime number in Python is just a number greater than 1 that’s only divisible by 1 and itself. If you're searching for a prime number program in Python or trying to understand the logic behind prime number code in Python, this guide will help. You'll learn to write a clean, working program for prime number in Python using simple loops and conditions.
We’ll also explain what makes a number prime, and how to optimize your code. Plus, if you’re aiming to build your Python basics for real-world use, check out our Data Science Courses and Machine Learning Courses for hands-on learning with logic-based problems.
def is_prime(number):
"""
Check if a given number is prime using for-else statement.
Args:
number (int): The number to be checked for primality.
Returns:
bool: True if the number is prime, False otherwise.
"""
# Handle special cases
if number < 2:
return False
# Check for divisibility from 2 to the square root of the number
for divisor in range(2, int(number**0.5) + 1):
# If number is divisible by any divisor, it's not prime
if number % divisor == 0:
return False
else:
# This block executes only if no divisors are found
return True
# Test the function with different numbers
test_numbers = [2, 3, 4, 5, 7, 11, 12, 17, 20, 29]
print("Prime Number Checker Results:")
for num in test_numbers:
result = is_prime(num)
print(f"{num} is {'prime' if result else 'not prime'}")
Output:
Prime Number Checker Results:
2 is prime
3 is prime
4 is not prime
5 is prime
7 is prime
11 is prime
12 is not prime
17 is prime
20 is not prime
29 is prime
If you're exploring Python through basic exercises and want to see how it's used in real-world data science problems, consider learning more through a structured program in Data Science and Machine Learning.
Explanation of Code
Key Points About the For-Else Mechanism
Related Reads:
def is_prime(number):
# Check if the number is less than 2
# Numbers less than 2 are not prime
if number < 2:
return False
# Initialize the flag as True
# We assume the number is prime until proven otherwise
is_prime_flag = True
# Check for divisors from 2 to the square root of the number
# We only need to check up to square root for efficiency
for i in range(2, int(number**0.5) + 1):
# If the number is divisible by any value, it's not prime
if number % i == 0:
# Set the flag to False
is_prime_flag = False
# Exit the loop as soon as a divisor is found
break
# Return the final state of the flag
return is_prime_flag
# Test the function with different numbers
test_numbers = [2, 3, 4, 5, 7, 10, 11, 13, 17, 20]
# Print primality of each number
for num in test_numbers:
print(f"{num} is {'prime' if is_prime(num) else 'not prime'}")
Output:
2 is prime
3 is prime
4 is not prime
5 is prime
7 is prime
10 is not prime
11 is prime
13 is prime
17 is prime
20 is not prime
Explanation of Code
Initial Check
Flag Initialization
Divisibility Check
Flag Modification
Result Return
Key Advantages of Flag Variable
“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”
def is_prime(number):
# Handle edge cases
if number < 2:
return False
# Check for divisibility from 2 to square root of the number
for i in range(2, int(number**0.5) + 1):
# If number is divisible by any value, it's not prime
if number % i == 0:
# Break the loop as soon as a divisor is found
break
# If no divisor found, continue checking
continue
else:
# If loop completes without finding divisors, number is prime
return True
# If loop breaks due to finding a divisor, number is not prime
return False
# Test the function with various numbers
test_numbers = [2, 3, 4, 5, 7, 10, 11, 13, 17, 20]
print("Prime Number Checking Results:")
for num in test_numbers:
result = is_prime(num)
print(f"{num} is {'prime' if result else 'not prime'}")
Output:
Prime Number Checking Results:
2 is prime
3 is prime
4 is not prime
5 is prime
7 is prime
10 is not prime
11 is prime
13 is prime
17 is prime
20 is not prime
Explanation of Code
Related Read:
def is_prime(number):
# Check if the number is less than 2 (not prime)
if number < 2:
return False
# Initialize the divisor
divisor = 2
# Use while loop to check divisibility
while divisor * divisor <= number:
# Check if the number is divisible by the current divisor
if number % divisor == 0:
# If divisible, it's not a prime number
return False
# Increment the divisor
divisor += 1
# If no divisors found, the number is prime
return True
# Test the function
test_numbers = [2, 3, 4, 5, 7, 10, 11, 13, 17, 20]
# Print prime status for each number
for num in test_numbers:
if is_prime(num):
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
Output:
2 is a prime number
3 is a prime number
4 is not a prime number
5 is a prime number
7 is a prime number
10 is not a prime number
11 is a prime number
13 is a prime number
17 is a prime number
20 is not a prime number
Explanation of Code
Function Definition
Initial Check
While Loop Mechanism
Divisibility Check
Divisor Increment
Prime Confirmation
Related Read
import math
def is_prime_using_math(number):
"""
Check if a given number is prime using the math module.
A prime number is a natural number greater than 1 that is only divisible by 1 and itself.
This method uses mathematical properties to efficiently check primality.
"""
# Handle special cases
if number <= 1:
return False
# 2 is the only even prime number
if number == 2:
return True
# Even numbers greater than 2 are not prime
if number % 2 == 0:
return False
# Use math.isqrt to find the integer square root efficiently
# We only need to check divisors up to the square root of the number
sqrt_number = math.isqrt(number)
# Check for divisibility by odd numbers up to the square root
for divisor in range(3, sqrt_number + 1, 2):
# If the number is divisible by any odd number, it's not prime
if number % divisor == 0:
return False
# If no divisors are found, the number is prime
return True
# Example usage and demonstration
def demonstrate_prime_checking():
# List of numbers to test
test_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 17, 19, 20, 29]
print("Prime Number Checking Results:")
print("-" * 30)
for num in test_numbers:
result = is_prime_using_math(num)
print(f"{num} is {'prime' if result else 'not prime'}")
# Run the demonstration
demonstrate_prime_checking()
Output:
Prime Number Checking Results:
------------------------------
1 is not prime
2 is prime
3 is prime
4 is not prime
5 is prime
6 is not prime
7 is prime
8 is not prime
9 is not prime
10 is not prime
11 is prime
12 is not prime
13 is prime
17 is prime
19 is prime
20 is not prime
29 is prime
Explanation
def is_prime_recursive(n, divisor=None):
"""
Check if a number is prime using recursive approach
Args:
n (int): The number to check for primality
divisor (int, optional): The current divisor to check against.
Defaults to None for initial call.
Returns:
bool: True if the number is prime, False otherwise
"""
# Handle special cases
if n <= 1:
return False
# If no divisor specified, start with square root of n
if divisor is None:
divisor = int(n ** 0.5)
# Base cases
# If we've checked all potential divisors successfully, the number is prime
if divisor == 1:
return True
# If the number is divisible, it's not prime
if n % divisor == 0:
return False
# Recursively check with the next lower divisor
return is_prime_recursive(n, divisor - 1)
# Test the function with different numbers
test_numbers = [2, 3, 4, 7, 10, 17, 20, 29]
print("Prime Number Recursion Test Results:")
for num in test_numbers:
result = is_prime_recursive(num)
print(f"{num} is {'prime' if result else 'not prime'}")
Output:
Prime Number Recursion Test Results:
2 is prime
3 is prime
4 is not prime
7 is prime
10 is not prime
17 is prime
20 is not prime
29 is prime
Explanation
The recursive approach to checking prime numbers involves systematically testing potential divisors from the square root of the number down to 1. Instead of using a loop, we use recursive function calls to check divisibility.
Key Recursive Strategy:
Code Breakdown:
Recursion Logic:
Step-by-Step Explanation:
Related Read:
pip install sympy
# Import the isprime function from sympy library
from sympy import isprime
# Function to demonstrate prime number checking
def check_prime_numbers():
# Test various numbers to demonstrate isprime() functionality
test_numbers = [2, 7, 10, 17, 20, 29, 100, 997]
# Iterate through each number and check its primality
for number in test_numbers:
# Use isprime() to determine if the number is prime
if isprime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
# Call the function to run the demonstration
check_prime_numbers()
Output:
2 is a prime number.
7 is a prime number.
10 is not a prime number.
17 is a prime number.
20 is not a prime number.
29 is a prime number.
100 is not a prime number.
997 is a prime number.
Explanation of Code
Import the Method:
Function Creation:
Number Selection:
Primality Testing:
Method Advantages:
# Large number primality test
large_number = 104729
print(f"{large_number} is prime: {isprime(large_number)}")
# Interactive user input
def interactive_prime_check():
try:
number = int(input("Enter a number to check if it's prime: "))
if isprime(number):
print(f"{number} is a prime number!")
else:
print(f"{number} is not a prime number.")
except ValueError:
print("Please enter a valid integer.")
Output:
104729 is prime: True
Method | Time Complexity | Space Complexity | Use Case |
If-Else/For-Else | O(sqrt(n)) | O(1) | Suitable for small inputs. |
Flag Variable | O(sqrt(n)) | O(1) | Beginner-friendly approach. |
Break and Continue | O(sqrt(n)) | O(1) | Reduces unnecessary checks. |
While Loop | O(sqrt(n)) | O(1) | Useful when loop iteration is required. |
Math Module | O(sqrt(n)) | O(1) | Enhances precision for large numbers. |
Recursion | O(sqrt(n)) | O(n) (stack memory) | For functional programming enthusiasts. |
sympy.isprime() | O(sqrt(n)) to O(log(n)^3) | O(1) | Best for large datasets and performance. |
Note: The complexity of sympy.isprime() varies based on its internal optimizations for small and large numbers.
Related Read:
1. Which of the following is a prime number?
a) 4
b) 6
c) 7
d) 9
2. What is the output of the code: print(5 % 2)?
a) 2
b) 0
c) 1
d) 5
3. What does the following function check?
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
a) Checks if a number is even
b) Checks if a number is composite
c) Checks if a number is prime
d) Checks if a number is odd
4. Which loop is best suited for checking if a number is prime?
a) `while` loop
b) `for` loop
c) `do-while` loop
d) `None`
5. What will be the output of:
def check_prime(n):
for i in range(2, n):
if n % i == 0:
print("Not Prime")
break
else:
print("Prime")
check_prime(11)
a) Prime
b) Not Prime
c) Error
d) Nothing
6. Which Python keyword is used to exit a loop early in a prime number check?
a) `continue`
b) `exit`
c) `return`
d) `break`
7. What is the time complexity of a basic prime number program in Python using a loop up to n?
a) O(1)
b) O(log n)
c) O(n)
d) O(n²)
8. What change improves the performance of this basic check?
for i in range(2, n):
if n % i == 0:
a) Loop till n//2
b) Loop till n-1
c) Loop till sqrt(n)
d) Loop from 0 to n
9. You need a function that returns a list of all prime numbers from 1 to 100. What Python construct is best?
a) `lambda`
b) `while` loop
c) `for` loop with list
d) `try-except`
10. A user inputs a number. You want to check if it’s prime and print the result. Which line is correct?
a) `if is_prime(num): print("Prime")`
b) `if prime(num): print("Yes")`
c) `if num == prime: print("True")`
d) `print(prime(num))`
11. You’re asked to optimize a prime number code for large inputs. What should you use?
a) Sieve of Eratosthenes
b) Factorial function
c) GCD algorithm
d) Binary search
Understanding how to check for a Prime Number in Python is a fundamental exercise that sharpens your problem-solving and optimization skills. This tutorial has walked you through various methods, from the simple trial division to more efficient, optimized approaches.
By building and refining a program for prime number in Python, you're not just solving a classic coding challenge, you're mastering core concepts like loops, conditionals, and computational efficiency. Keep practicing with these techniques, and you'll be well-prepared for more complex algorithmic problems in your programming journey.
With upGrad, you can access global standard education facilities right here in India. upGrad also offers free Data Science courses that come with certificates, making them an excellent opportunity if you're interested in data science and machine learning.
By enrolling in upGrad's Python courses, you can benefit from the knowledge and expertise of some of the best educators from around the world. These instructors understand the diverse challenges that Python programmers face and can provide guidance to help you navigate them effectively.
So, reach out to an upGrad counselor today to learn more about how you can benefit from a Python course.
Here are some of the best data science and machine learning courses offered by upGrad, designed to meet your learning needs:
Similar Reads: Top Trending Blogs of Python
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In other words, it cannot be formed by multiplying two smaller natural numbers. For example, 5 is a prime number because its only divisors are 1 and 5. The number 6, however, is not prime (it is a composite number) because it can be divided by 2 and 3. Understanding this definition is the first step in creating a program for prime number in Python.
By definition, a prime number must be a natural number greater than 1. The number 1 is excluded because it only has one distinct positive divisor (itself), whereas a prime number must have exactly two. If 1 were considered prime, the fundamental theorem of arithmetic (which states that every integer greater than 1 is either a prime number itself or can be represented as a product of prime numbers) would no longer be unique. 0 is not prime because it can be divided by any non-zero integer.
To determine if a number is a Prime Number in Python, you need to write code that checks if it is divisible by any integer other than 1 and itself. The most common method is trial division, where you create a loop that iterates from 2 up to the square root of the number. Inside the loop, you use the modulo operator (%) to check for divisibility. If any number in that range divides the input number evenly (i.e., the remainder is 0), then the number is not prime. If the loop completes without finding any divisors, the number is prime.
There is no single, simple algebraic formula that can generate all prime numbers. Prime numbers are a subject of deep mathematical study, and their distribution is complex. Instead of a formula, programmers use algorithms to find them. For generating a list of primes up to a certain limit, the most famous algorithm is the Sieve of Eratosthenes. For checking a single number, the best approach is an optimized trial division, which is the basis for any good program for prime number in Python.
The prime numbers between 0 and 100 are a classic set to generate when you are first learning to code. The complete list of these 25 prime numbers is: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, and 97. Writing a Python script to generate this list is an excellent beginner exercise.
There are many methods to check for a Prime Number in Python, each with different trade-offs in readability and efficiency. A simple approach is using a for loop with an if-else statement to check for divisors. You can also use a flag variable that gets toggled if a divisor is found. For more concise code, you can use a for-else loop, where the else block only runs if the loop completes without hitting a break. More advanced methods include using recursion or pre-built functions from libraries like SymPy.
Using a function is the best practice for creating a reusable and clean program for prime number in Python. A well-designed function, say is_prime(n), would take an integer n as input and return a boolean value (True or False). Inside the function, you would encapsulate all the logic, including handling edge cases (like numbers less than 2) and implementing the optimized trial division loop. This makes your main code much more readable, as you can simply call is_prime(number) to get a clear answer.
While loops are the most intuitive way to implement the logic, you can check for a Prime Number in Python without writing an explicit loop by using more advanced techniques. Recursion is one method, where a function calls itself to perform the divisibility checks. A more practical and common approach is to use a pre-existing, highly optimized function from a library. For example, the SymPy library has a function sympy.isprime() that can determine if a number is prime very efficiently.
The Sieve of Eratosthenes is an ancient and highly efficient algorithm for finding all prime numbers up to a specified limit. To implement it, you start by creating a boolean list (or array) representing all numbers from 0 to your limit, initially marking them all as potentially prime. You then start with the first prime, 2, and iterate through the list, marking all multiples of 2 as not prime. You then move to the next unmarked number, 3, and do the same. This process continues until you have iterated through the list, leaving only the prime numbers marked as true.
The time complexity of a program for prime number in Python depends on the algorithm used. A naive approach that checks for divisors from 2 up to n-1 has a time complexity of O(n). A significantly better and more common approach is to check for divisors only up to the square root of n, which improves the time complexity to O(√n). The Sieve of Eratosthenes algorithm, which generates all primes up to n, is even more efficient, with a time complexity of O(n log log n).
The fastest method depends on the size of the number being checked. For most practical purposes and numbers up to a very large size, an optimized trial division is sufficient. This involves checking for divisibility only by 2 and then by odd numbers up to the square root of the number. For extremely large numbers, such as those used in cryptography, probabilistic primality tests like the Miller-Rabin test are much faster, as they can determine the likelihood of a number being prime with a very high degree of certainty.
There are two main ways to generate a list of prime numbers. To generate primes within a finite range (e.g., all primes under 1,000), the most efficient method is to use an algorithm like the Sieve of Eratosthenes. To generate an infinite sequence of primes, you can create a generator function. This function would yield primes one at a time as they are found, which is very memory-efficient as it doesn't store the entire list in memory.
A composite number is a natural number greater than 1 that is not a prime number. In other words, it is a number that has at least one positive divisor other than 1 and itself. For example, 9 is a composite number because it can be divided by 3. When you write a program for prime number in Python, your logic is essentially trying to determine if a number is composite; if it's not, and it's greater than 1, then it must be prime.
This is a crucial optimization for any primality test. If a number n has a divisor d that is larger than its square root (√n), then n must also have another divisor c such that d * c = n. In this case, c must be smaller than the square root of n. Therefore, if n has any divisors, at least one of them must be less than or equal to its square root. This means we don't need to check any further, which dramatically reduces the number of iterations in our program for prime number in Python.
Twin primes are a pair of prime numbers that differ by exactly 2. For example, (3, 5), (5, 7), and (11, 13) are all twin prime pairs. To find them in Python, you can first generate a list of all prime numbers up to a certain limit. Then, you can iterate through that list and check if the difference between a prime and the next prime in the list is equal to 2.
Python's standard library does not have a dedicated, built-in function to check for primality. However, the math module provides helpful functions like math.isqrt() for efficient square root calculation, which is useful in a program for prime number in Python. For more advanced or high-performance primality testing, it is common to use third-party libraries like SymPy or gmpy2, which have highly optimized functions for this purpose.
Prime numbers are absolutely critical in the field of cryptography, which is the foundation of modern computer security. Public-key cryptography algorithms, such as RSA, rely on the mathematical properties of large prime numbers. The security of these systems is based on the fact that it is computationally very easy to multiply two large prime numbers together, but it is extremely difficult to do the reverse—that is, to factor the product back into its original prime components.
A "Pythonic" approach often favors readability and conciseness. Instead of a complex loop with a flag, you could write a function that uses a generator expression with the all() function. For example, all(n % i != 0 for i in range(2, int(n**0.5) + 1)). This single line of code checks if all the potential divisions have a non-zero remainder. This is a more advanced but elegant way to structure your Prime Number in Python logic.
Prime numbers are a fantastic topic for honing your algorithmic thinking. You can start by implementing the basic trial division method, then move on to optimizing it. After that, challenge yourself to implement the Sieve of Eratosthenes. For a more structured learning path, you can explore the programming and algorithms courses offered by upGrad, which often include these types of classic problems and provide expert guidance on different optimization techniques.
The main takeaway is not just about identifying a Prime Number in Python, but about learning the fundamentals of algorithmic thinking and optimization. The process of starting with a simple, brute-force solution and then refining it by applying mathematical properties (like checking only up to the square root) is a perfect example of the problem-solving mindset that is at the heart of computer science. It's a foundational exercise that teaches you how to write code that is not just correct, but also efficient.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
Recommended Programs