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 called 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 Python program checks 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)
Within the for loop, there is an If statement to check whether the Number divisible by i is exactly equal to 0 or not. If the condition is True, then Count value incremented, and then Break Statement 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 Python Program to find Prime Number 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 become 3
Do the same for the remaining For Loop iterations
Next, it enters in to Python If statement. if(count == 0 && Number != 1 ). In all the above iterations, If condition failed, so Count Value has not incremented from initialized o. And the Number that we used is 365 (not zero). So, the condition is True, which means Prime Number.
Python Program to find Prime Number using While Loop
This Python program for Prime number is the same as the above. We just replaced the For loop in the above python program 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)
Python Program to find Prime Number using Functions
This Python prime number program is the same as the first example. However, we separated the logic by defining the 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)