Python Prime Number Program: Code, Examples, and Explanation
-
By Devraj
-
27th October 2026
Mastering the Fundamentals: Why Prime Number Programs Are Essential for Python Learners
Whether you are preparing for a technical Python interview or building a strong foundation through a comprehensive Python training program, mastering logic-based exercises is a crucial milestone. A Python prime number program checks whether a number is prime by determining if it has exactly two factors: 1 and itself. In Python, you can check prime numbers using a for loop, a while loop, a function, recursion, or the square root method. This guide explains each approach with simple Python code, examples, outputs, and step-by-step explanations for beginners.
Want to strengthen your Python skills?
Explore our courses at Skill Hives and get trained by experts.
What Is a Prime Number in Python?
A prime number is a whole number greater than 1 that has exactly two factors: 1 and itself.
For example, 2, 3, 5, 7, 11, and 13 are prime numbers because they cannot be divided evenly by any other positive whole number apart from 1 and themselves.
Here are some examples:
| Number | Factors | Prime Number? |
|---|---|---|
| 2 | 1, 2 | Yes |
| 3 | 1, 3 | Yes |
| 4 | 1, 2, 4 | No |
| 5 | 1, 5 | Yes |
| 9 | 1, 3, 9 | No |
| 11 | 1, 11 | Yes |
Important: The number 1 is not prime because it has only one positive factor. Negative numbers, zero, and one are also not prime numbers.
Understanding this definition makes it easier to write a prime number program in Python.
1. Prime Number Program in Python for Beginners
The easiest way to understand prime numbers is to write a basic program that checks whether a given number is prime.
Python Prime Number Code
num = 7
if num > 1:
for i in range(2, num):
if num % i == 0:
print(num, “is not a prime number”)
break
else:
print(num, “is a prime number”)
else:
print(num, “is not a prime number”)
Output
7 is a prime number
Explanation
- num = 7 stores the number to check.
- if num > 1 ensures that the number is eligible to be prime.
- range(2, num) checks possible divisors starting from 2.
- num % i == 0 checks whether the number divides evenly by another number.
- break stops the loop when a divisor is found.
- The else block attached to the for loop runs if the loop finishes without encountering break.
Since 7 is not divisible evenly by 2, 3, 4, 5, or 6, it is a prime number.
This example is a good starting point for students learning how to check prime numbers in Python.
2. Python Program to Check Whether a Number Is Prime or Not Using User Input
Instead of checking a fixed number, you can ask the user to enter a number. Python’s input() function accepts the value, while int() converts it into an integer.
Code
num = int(input(“Enter a number: “))
if num > 1:
for i in range(2, num):
if num % i == 0:
print(num, “is not a prime number”)
break
else:
print(num, “is a prime number”)
else:
print(num, “is not a prime number”)
Output
Enter a number: 13
13 is a prime number
How Does It Work?
Suppose the user enters 13. The program checks whether 13 is divisible by any integer from 2 to 12. Because none of these numbers divides 13 evenly, the program identifies it as prime. If the user enters 12, the program finds that 12 is divisible by 2 and prints that it is not prime.
This example demonstrates a Python program to check prime numbers with user input.
3. Python Program to Check Prime Number Using a For Loop
A for loop repeats a block of code for each value in a sequence. It is one of the most common ways to check whether a number is prime.
Code
num = 17
is_prime = True
if num <= 1:
is_prime = False
else:
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, “is a prime number”)
else:
print(num, “is not a prime number”)
Output
17 is a prime number
Explanation
The variable is_prime initially stores True, assuming the number may be prime. The loop tests possible divisors from 2 to num – 1. If a divisor is found, the variable changes to False, and the loop stops. If no divisor is found, the number is prime.
This method is useful for students who want to understand the relationship between loops, conditions, and prime number logic in Python.
4. Python Program to Check Prime Number Using a While Loop
You can also use a while loop to check whether a number is prime. A while loop continues running as long as its condition is true.
Code
num = 19
i = 2
is_prime = True
if num <= 1:
is_prime = False
else:
while i < num:
if num % i == 0:
is_prime = False
break
i += 1
if is_prime:
print(num, “is a prime number”)
else:
print(num, “is not a prime number”)
Output
19 is a prime number
Explanation
The variable i starts at 2 because every integer is divisible by 1, and checking 1 does not help determine whether a number is prime. The loop checks whether num is divisible by i. If it is, the number is not prime. Otherwise, i += 1 moves to the next possible divisor. The loop ends when it reaches the number itself.
This example explains how to write a Python program to check prime number using a while loop.
5. Python Program to Check Prime Number Using a Function
A function allows you to write reusable code. Instead of repeating the same logic throughout a program, you can create a function that checks whether a number is prime.
Code
def is_prime(num):
if num <= 1:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
number = int(input(“Enter a number: “))
if is_prime(number):
print(number, “is a prime number”)
else:
print(number, “is not a prime number”)
Output
Enter a number: 23
23 is a prime number
Explanation
The is_prime() function receives a number as an argument.
- If the number is less than or equal to 1, the function returns False.
- If any divisor is found, the function returns False.
- If the loop finishes without finding a divisor, the function returns True.
The main program calls the function and displays the result. Using a function makes the code easier to reuse, test, and maintain.
6. Python Program to Check Prime Number Using Recursion
Recursion occurs when a function calls itself to solve a problem. You can use recursion to check whether a number has a divisor.
Code
def is_prime(num, divisor=2):
if num <= 1: return False if divisor * divisor > num:
return True
if num % divisor == 0:
return False
return is_prime(num, divisor + 1)
number = int(input(“Enter a number: “))
if is_prime(number):
print(number, “is a prime number”)
else:
print(number, “is not a prime number”)
Output
Enter a number: 29
29 is a prime number
Explanation
The function starts checking divisors at 2. If the square of the current divisor is greater than the number, no additional divisor needs to be checked, so the function returns True. If the number divides evenly by the current divisor, the function returns False. Otherwise, it calls itself with the next divisor.
Note: Recursion is useful for understanding recursive functions, but a loop is generally a more practical choice for checking prime numbers in Python.
7. Optimized Python Program to Check Prime Number Using Square Root
Checking every number from 2 to num – 1 works, but it can take unnecessary time.
A faster approach checks divisors only up to the square root of the number. This works because if a number has a factor greater than its square root, it must also have a corresponding factor smaller than its square root.
Code
import math
def is_prime(num):
if num <= 1:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, math.isqrt(num) + 1, 2):
if num % i == 0:
return False
return True
number = int(input(“Enter a number: “))
if is_prime(number):
print(number, “is a prime number”)
else:
print(number, “is not a prime number”)
Output
Enter a number: 97
97 is a prime number
Why Is This Program Faster?
The optimized program uses three improvements:
- It immediately rejects numbers less than or equal to 1.
- It handles 2 separately and rejects other even numbers.
- It checks only odd divisors up to the integer square root of the number.
For example, when checking 97, the program only needs to test odd divisors up to 9.
The time complexity is O(√n), making this an efficient approach for checking individual numbers. This method is particularly useful when you want an optimized Python program to check prime numbers.
8. Python Program to Find Prime Numbers Between Two Numbers
Sometimes, you need to find every prime number within a specific range instead of checking just one number.
The following program accepts a starting number and an ending number and prints all the prime numbers between them, including both endpoints when they are prime.
Code
start = int(input(“Enter the starting number: “))
end = int(input(“Enter the ending number: “))
for num in range(max(2, start), end + 1):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=” “)
Output
Enter the starting number: 10
Enter the ending number: 30
11 13 17 19 23 29
Explanation
The outer loop visits every number in the requested range. For each number, the inner loop checks possible divisors up to its square root. If a divisor is found, the number is not prime. Otherwise, the number is printed.
This example covers the Python program to find prime numbers between two numbers and the Python program to print prime numbers in a given range.
9. Python Program to Print Prime Numbers from 1 to 100
One common beginner programming exercise is printing all prime numbers between 1 and 100.
Code
for num in range(2, 101):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=” “)
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Explanation
The program starts at 2 because 1 is not prime. For every number up to 100, it checks whether any integer from 2 to the square root divides it evenly. If no divisor is found, the number is printed. The result contains 25 prime numbers.
10. Python Program to Find the First N Prime Numbers
You may also need to print a specific number of prime numbers rather than primes within a fixed range.
For example, if the user enters 5, the program should print the first five prime numbers.
Code
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
n = int(input(“How many prime numbers do you want? “))
count = 0
num = 2
while count < n:
if is_prime(num):
print(num, end=” “)
count += 1
num += 1
Output
How many prime numbers do you want? 5
2 3 5 7 11
Explanation
The program begins with 2 and checks each number using the is_prime() function. Whenever a prime number is found, the program prints it and increases the count. The loop continues until the requested number of primes has been printed.
If the user enters zero or a negative number, the loop prints no prime numbers. For a beginner-friendly application, you could add input validation to explain that the requested count should be positive.
11. Python Program to Find Prime Numbers in a List
What if you already have a list of numbers and want to identify which ones are prime?
You can use a function and a for loop to check every item in the list.
Code
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
numbers = [2, 4, 7, 9, 11, 15, 17, 20]
prime_numbers = [
num for num in numbers if is_prime(num)
]
print(“Prime numbers:”, prime_numbers)
Output
Prime numbers: [2, 7, 11, 17]
Explanation
The program checks every number in the list using the is_prime() function. If the function returns True, the number is included in prime_numbers. Otherwise, it is excluded.
This technique is useful when working with lists, datasets, and collections of numbers.
12. Understanding Prime Number Logic in Python
The logic behind a prime number program is straightforward once you understand divisibility.
Suppose you want to check whether 11 is prime.
- Start with the number 11.
- Check whether it is greater than 1.
- Test whether it is divisible by 2.
- Continue checking possible divisors up to the square root of 11.
- Since no divisor is found, identify 11 as a prime number.
Now consider 15. It is divisible by 3 and 5, so it is not prime.
The % operator plays an important role in this process.
For example:
print(10 % 2)
print(11 % 2)
Output:
0
1
When the remainder is 0, the number divides evenly by the divisor. When the remainder is not 0, it does not divide evenly.
Remember: A number is prime if it is greater than 1 and has no positive divisors other than 1 and itself.
13. Prime Number Algorithms in Python: Which Method Should You Use?
Different approaches are suitable for different learning and programming needs.
| Method | Best Use | Time Complexity |
|---|---|---|
| Basic for loop | Understanding prime number logic | O(n) |
| while loop | Practising conditional loops | O(n) |
| Function | Reusing prime-checking logic | Depends on the checking method |
| Recursion | Learning recursive programming | O(√n) with the optimized method shown above |
| Square root method | Checking individual numbers efficiently | O(√n) |
| Range-based program | Finding multiple prime numbers | Depends on the range and checking method |
The basic loop is a good starting point for beginners. The square root method is generally a better choice when you want to check individual numbers efficiently.
If you need to generate many prime numbers within a large range, the Sieve of Eratosthenes is another algorithm worth studying. It finds primes by marking multiples of smaller prime numbers rather than testing every candidate independently.
14. Common Mistakes to Avoid When Writing a Prime Number Program
Beginners sometimes make small mistakes that cause incorrect results.
Mistake 1: Treating 1 as a Prime Number
The number 1 is not prime. Always handle numbers less than or equal to 1 separately.
Mistake 2: Starting the Divisor Loop at 1
Every integer is divisible by 1, so checking 1 does not help determine whether a number is prime. Start checking at 2.
Mistake 3: Forgetting to Stop When a Divisor Is Found
Once a divisor is found, you already know that the number is not prime. Use break or return False from a function.
Mistake 4: Using the Wrong Range Limit
Python’s range() excludes its ending value. To include the integer square root when needed, use math.isqrt(num) + 1 or int(num ** 0.5) + 1.
Mistake 5: Forgetting That 2 Is Prime
Two is the smallest prime number and the only even prime number. A program that rejects every even number without handling 2 separately will produce an incorrect result.
Learn Python Programming with Skill Hives
Learning Python becomes easier when you practise concepts through small programs and gradually move to more advanced problems. At Skill Hives, students can build their programming knowledge by studying fundamental concepts such as variables, loops, conditional statements, functions, lists, and algorithms.
Start by writing a basic prime number program, test it with different inputs, and then improve it using functions and the square root method.
Want to strengthen your programming skills?
Connect with Skill Hives to discuss your learning goals and explore suitable training options.
Frequently Asked Questions
1. How do you check whether a number is prime in Python?
You can check whether a number is prime by testing whether it is divisible by any integer from 2 up to its square root. If no divisor is found and the number is greater than 1, it is prime.
2. What is the simplest prime number program in Python?
A simple prime number program uses an if statement and a for loop to test divisors. If any divisor divides the number evenly, the number is not prime. Otherwise, it is prime.
3. How do you print prime numbers from 1 to 100 in Python?
Use a loop to check each number from 2 to 100. Test possible divisors up to the square root of each number and print the numbers that have no divisors other than 1 and themselves.
4. Can we check prime numbers using a while loop in Python?
Yes. A while loop can test possible divisors one at a time. Increase the divisor after each unsuccessful check and stop when a divisor is found or the required limit is reached.
5. What is the most efficient way to check a prime number in Python?
For checking an individual number, testing divisors only up to its square root is much more efficient than checking every smaller number. Skipping even divisors after handling 2 separately makes the method more efficient.
6. Why is 1 not considered a prime number?
A prime number must have exactly two distinct positive factors: 1 and itself. The number 1 has only one positive factor, so it is not prime.