DEV Community

Cover image for How to Find a Prime Number in Python — A Thinking Journey
Kathirvel S
Kathirvel S

Posted on

How to Find a Prime Number in Python — A Thinking Journey

Introduction

Understanding how to find prime numbers is one of the best ways to develop logical thinking in programming. It looks simple on the surface, but it teaches you how to break a problem into smaller steps, build a solution gradually, and then improve it into a clean and reusable structure.

In this blog, we will not jump directly into code. Instead, we will start from basic thinking, slowly convert that thinking into logic, and finally refine it into a proper Python program using functions and loops. The goal is not just to find prime numbers, but to understand how programming logic is actually built in real development.


1. Understanding the Problem First

Before writing anything in Python, we need to understand what a prime number actually means.

A prime number is a number that:

  • is greater than 1
  • has exactly two divisors: 1 and itself

So the real question becomes:

How do we check whether a number has any divisors other than 1 and itself?

That is the core problem we are trying to solve.


2. Thinking Like a Human Before Coding

Let’s take a number, for example 13.

To check if 13 is prime, we naturally try dividing it by smaller numbers:

  • 2 → does not divide 13
  • 3 → does not divide 13
  • 4 → does not divide 13
  • 5 → does not divide 13
  • and so on

If none of these numbers divide 13 completely, then 13 is prime.

So the logic is simple:

Try dividing the number by possible candidates and see if any divide it perfectly.


3. Turning Thinking into a Basic Algorithm

From the above idea, we can form a basic structure:

We need:

  • a number to test
  • a variable that moves through possible divisors
  • a way to detect whether a divisor exists

We start checking from 2 because every number is divisible by 1 anyway.

We also do not need to check beyond half of the number, because a number cannot have a divisor greater than half (except itself).

So the idea becomes:

  • Start divisor from 2
  • Go up to number // 2
  • If any number divides it evenly, it is not prime

4. First Working Logic (Direct Implementation)

Now we translate the idea into Python.

We introduce:

  • number: the value we are testing
  • divisor: the number we try dividing with
  • divisor_count: how many divisors we find

If divisor_count stays zero, the number is prime.

number = 13
divisor = 2
divisor_count = 0

while divisor <= number // 2:
    if number % divisor == 0:
        print("divisor found:", divisor)
        divisor_count += 1
    divisor += 1

if divisor_count == 0:
    print("Prime")
else:
    print("Not Prime")
Enter fullscreen mode Exit fullscreen mode

Flow Chart:

Start
  ↓
Initialize number, divisor = 2, divisor_count = 0
  ↓
Check divisor <= number//2
  ↓
Is number divisible by divisor?
      ↓ Yes → increment divisor_count
      ↓ No  → continue
  ↓
Increase divisor
  ↓
Repeat loop
  ↓
If divisor_count == 0 → Prime
Else → Not Prime
  ↓
End
Enter fullscreen mode Exit fullscreen mode

5. Understanding What Happens Here

This logic works like a manual test:

We are checking every possible divisor one by one.

If even one divisor divides the number completely, we mark it as non-prime.

Otherwise, it is prime.

So effectively:

  • No divisors found → Prime
  • At least one divisor found → Not Prime

6. The Problem With This Approach

Although this works, it has a major issue.

If we want to check multiple numbers, we would need to repeat the same logic again and again.

This leads to:

  • repeated code
  • harder maintenance
  • low reusability

So we need a better structure.


7. Introducing Functions in Python

A function is a reusable block of code that performs a specific task.

Instead of rewriting logic every time, we can define it once and reuse it whenever needed.

From the official Python documentation:

A function is a group of statements that performs a specific task.

Reference:
https://docs.python.org/3/tutorial/controlflow.html#defining-functions


8. Simple Example to Understand Functions

Before applying it to primes, let’s understand a simple function idea.

def buy_nonveg():
    return "chicken"

bag = buy_nonveg()
print(bag)
Enter fullscreen mode Exit fullscreen mode

Flow Chart:

Call function buy_nonveg()
  ↓
Execute function body
  ↓
return "chicken"
  ↓
Store result in bag
  ↓
Print bag
  ↓
End
Enter fullscreen mode Exit fullscreen mode

9. Understanding the return Keyword

The return statement is used to send a result back from a function.

From Python documentation:

The return statement exits a function and optionally passes back an expression.

Reference:
https://docs.python.org/3/reference/simple_stmts.html#the-return-statement

In simple terms:

  • A function processes something
  • return sends the result back
  • after return, the function stops executing

You can think of it as:

Input → Processing → Output

return is the output step.


10. Converting Prime Logic into a Function

Now we take our earlier logic and wrap it inside a function so it becomes reusable.

def find_prime(no):
    div = 2
    divisors_count = 0

    while div <= no // 2:
        if no % div == 0:
            divisors_count += 1
        div += 1

    if divisors_count == 0:
        return True
    else:
        return False
Enter fullscreen mode Exit fullscreen mode

Flow Chart:

Start function find_prime(no)
  ↓
Initialize div = 2, divisors_count = 0
  ↓
Check div <= no//2
  ↓
Is no divisible by div?
      ↓ Yes → increment divisors_count
      ↓ No  → continue
  ↓
Increase div
  ↓
Repeat loop
  ↓
If divisors_count == 0
      ↓ Yes → return True
      ↓ No  → return False
  ↓
End function
Enter fullscreen mode Exit fullscreen mode

11. Understanding This Function

This function does the following:

  • takes a number as input
  • checks all possible divisors
  • counts how many divisors exist
  • returns True if no divisors are found
  • returns False otherwise

So now instead of writing full logic every time, we simply call this function.


12. Using the Function (But Still Not Efficient)

Now we try to use this function to check multiple numbers.

no = 2

result = find_prime(no)
if result == True:
    print(no)

no += 1
result = find_prime(no)
if result == True:
    print(no)

no += 1
result = find_prime(no)
if result == True:
    print(no)
Enter fullscreen mode Exit fullscreen mode

Flow Chart:

Start
  ↓
Set no = 2
  ↓
Call find_prime(no)
  ↓
If result == True → print no
  ↓
Increase no
  ↓
Repeat manually
  ↓
End
Enter fullscreen mode Exit fullscreen mode

13. The Problem Again

Even though logic is now reusable, usage is still repetitive.

We are still manually:

  • increasing numbers
  • calling function again and again

This is not scalable.

So we need another improvement.


14. Using a Loop to Remove Repetition

Instead of repeating the same steps, we can automate the process using a loop.

def find_prime(no):
    div = 2
    divisors_count = 0

    while div <= no // 2:
        if no % div == 0:
            divisors_count += 1
        div += 1

    return divisors_count == 0


no = 2

while no <= 10:
    if find_prime(no):
        print(no)
    no += 1
Enter fullscreen mode Exit fullscreen mode

Flow Chart:

Start
  ↓
Set no = 2
  ↓
Check no <= 10
  ↓
Call find_prime(no)
  ↓
If True → print no
  ↓
Increment no
  ↓
Repeat loop
  ↓
End when no > 10
Enter fullscreen mode Exit fullscreen mode

15. What Changed Here

Now the structure is much cleaner:

  • Loop handles number progression
  • Function handles prime checking
  • Output is handled separately

This separation is important in programming design.


16. Final Improved Version (Cleaner Logic)

We can further improve the function by removing unnecessary counting.

We only need to know whether a divisor exists or not.

def is_prime(n):
    if n < 2:
        return False

    div = 2
    while div <= n // 2:
        if n % div == 0:
            return False
        div += 1

    return True
Enter fullscreen mode Exit fullscreen mode

Flow Chart:

Start function is_prime(n)
  ↓
If n < 2 → return False
  ↓
Set div = 2
  ↓
Check div <= n//2
  ↓
If n % div == 0 → return False
  ↓
Increment div
  ↓
Repeat loop
  ↓
If no divisor found → return True
  ↓
End function
Enter fullscreen mode Exit fullscreen mode

And usage becomes:

for num in range(2, 11):
    if is_prime(num):
        print(num)
Enter fullscreen mode Exit fullscreen mode

Flow Chart:

Start
  ↓
Loop num from 2 to 10
  ↓
Call is_prime(num)
  ↓
If True → print num
  ↓
Repeat loop
  ↓
End
Enter fullscreen mode Exit fullscreen mode

17. Final Understanding

At a high level, prime checking is simply:

  • Try dividing the number
  • If anything divides it evenly → not prime
  • If nothing divides it → prime

Everything else in code is just structuring this idea properly.


18. Key Learning Path

What we built step by step:

  1. Manual reasoning
  2. Basic loop logic
  3. First implementation
  4. Identifying repetition problem
  5. Introducing functions
  6. Understanding return
  7. Refactoring into reusable design
  8. Removing redundancy with loops
  9. Final clean implementation

Conclusion

What looks like a simple “prime number program” is actually a complete demonstration of how programming logic evolves in real software development.

We started with raw human thinking, converted it into a working algorithm, noticed its limitations, introduced functions for reusability, and finally optimized it into a clean and scalable solution.

This is exactly how real developers think: not by writing perfect code at once, but by building, observing problems, and improving step by step.

If you understand this flow, you are not just learning prime numbers — you are learning how to think like a programmer.

Top comments (1)

Collapse
 
vinayagam_6a170db9281d526 profile image
Vinayagam

nice blog