Python Practice › Loop Programs › Program 31
Prime check with a loop
Write a Python program to check whether a number is prime using a loop.
Input
97, 91
Output
97 is prime 91 is not prime, divisible by 7
Approach
- Use
for ... else: theelseruns only if no divisor was found.
Solution
for n in [97, 91]: if n < 2: print(n, "is not prime") continue for d in range(2, int(n ** 0.5) + 1): if n % d == 0: print(n, "is not prime, divisible by", d) break else: print(n, "is prime")Output
97 is prime 91 is not prime, divisible by 7
Line by line
Lines 5-8
break stops the search at the first divisor.
Lines 9-10
The else belongs to the for; it runs only when the loop finished without break.
Learn the concept
New to this topic? Read the lesson, then come back.