In this article, we will show you, How to write a Python Program to Find Prime Number using For Loop, While Loop, and Functions.

Any natural number that is not divisible by any other number except 1 and itself is called as Prime Number in Python.

**Prime Numbers:** 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, 101, 103, 107, 109 etc

**TIP:** 2 is the only even prime number

## Python Program to find Prime Number using For Loop

This python program for Prime number allows the user to enter any integer value. Next, this program will check whether the given number is a Prime number or Not using For Loop.

# Python Program to find Prime Number Number = int(input(" Please Enter any Number: ")) count = 0 for i in range(2, (Number//2 + 1)): if(Number % i == 0): count = count + 1 break if (count == 0 and Number != 1): print(" %d is a Prime Number" %Number) else: print(" %d is not a Prime Number" %Number)

**OUTPUT**

**ANALYSIS**

Within the for loop, there is If statement to check, whether the Number divisible by i is exactly equal to 0 or not. If the condition is True then Count will be incremented and then Break Statement will be executed. Next, we used another If statement to check, whether Count is Zero and Number is Not equal to 1.

User entered integer in the above example is 365

**First Iteration: for i in range(2, 365//2)**

It means, for i in range (2, 182.5) – Condition is True

Now, Check the if condition – if (365%2 == 0). As you know, the condition is False

Next, i will become 3

Do the same for the remaining iterations

Next, it will enter in to If statement. * if(count == 0 && Number != 1 ). *In all the above iterations, If statement is failed so Count Value has not be incremented from initialized o. And the Number that we used is 365 (not zero). So condition is True, which means Prime Number

## Python Program to find Prime Number using While Loop

This program for Prime number in Python is same as above. We just replaced the For loop with While Loop

# Python Program to find Prime Number Number = int(input(" Please Enter any Number: ")) count = 0 i = 2 while(i <= Number//2): if(Number % i == 0): count = count + 1 break i = i + 1 if (count == 0 and Number != 1): print(" %d is a Prime Number" %Number) else: print(" %d is not a Prime Number" %Number)

**OUTPUT**

## Python Program to find Prime Number using Functions

This Python prime number program is same as first example. However, we separated the logic by defining new Function.

# Python Program to find Prime Number def finding_factors(Number): count = 0 for i in range(2, (Number//2 + 1)): if(Number % i == 0): count = count + 1 return count Num = int(input(" Please Enter any Number: ")) cnt = finding_factors(Num) if (cnt == 0 and Num != 1): print(" %d is a Prime Number" %Num) else: print(" %d is not a Prime Number" %Num)

**OUTPUT**