Prime Number Program in Python Using for Loop

Program to Check Prime Number Program in Python using a for loop if else statement

num = 407 
if num > 1:
   # check for factors
   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")
       
# if input number is less than
# or equal to 1, it is not prime
else:
   print(num,"is not a prime number")
Output :
407 is not a prime number

Code Explanation: Prime Number Program using a for loop else statement in Python

In this program, we have stored a number into variable num; you can even take user input here. Here we will check if the number is greater than 1 or not; this is just because if the number is less than or equal to 1 then it is not a prime number. Now we will check for factors; we have a for loop and i as a counter, and the loop will start from 2 and run till num-1 as in range the last number is opted out.

Then inside the loop, we will check if the number is divisible by counter i or not, if it is divisible by the counter, then it is not a prime number and we will print that num is not a prime number. And we will break the loop. Now we will write another statement. Inside else we will write it is a prime number.

Outside the indent of the for loop, we have another statement for main where we have checked if num is greater than 1 if not, then the number is not a prime number, which we have printed in the else statement. Run the program, and you will get 407 is not a prime number.

It works on the logic that the else clause of the for loop runs if and only if we don’t break out the for loop. That condition is met only when no factors are found, which means that the given number is prime.

Now you know what a prime number is and how to check if a number is a prime number or not.

Video Explanation of Prime Number Program in Python using a for loop if else statement

About The Author