Python Practice › Loop Programs › Program 31

Prime check with a loop

EasyLoop Programs · 31 of 90

Write a Python program to check whether a number is prime using a loop.

Advertisement
Input
97, 91
Output
97 is prime
91 is not prime, divisible by 7

Approach

  1. Use for ... else: the else runs only if no divisor was found.

Solution

Python
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.

More loop programs

← All 90 Loop Programs

Leave a Comment