Professional Documents
Culture Documents
Doc
Doc
Example to check whether an integer is a prime number or not using for loop and
if...else statement. If the number is not prime, it's explained in output why
it is not a prime number.
To understand this example, you should have the knowledge of the following
Python programming topics:
num = 29
if num == 1:
print(num, "is not a prime number") elif num > 1:
# check for factors
for i in range(2, num): if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop break
29 is a prime number
In this program, we have checked if num is prime or not. Numbers less than or
equal to 1 are not prime numbers. Hence, we only proceed if the num is greater
than 1.
Outside the loop, we check if flag is True or False. If it is True, num is not a
prime number.
If it is False, num is a prime number.
Note: We can improve our program by decreasing the range of numbers where we
look for factors.
You can change the value of variable num in the above source code to check
whether a number is prime or not for other integers.
In Python, we can also use the for...else statement to do this task without
using an additional flag variable.
if num == 1:
print(num, "is not a prime number") elif num > 1:
# check for factors
for i in range(2,num): if (num % i) == 0:
print(num,"is not a prime number") print(i,"times",num//i,"is",num) break
else:
print(num,"is 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.