Python Practice › Basic Programs › Program 28

Check a prime number

MediumBasic Programs · 28 of 40

Write a Python program to check whether a number is prime (greater than 1 and divisible only by 1 and itself).

Advertisement
Input
29, 33, 1, 97
Output
29 True
33 False
1 False
97 True

Approach

  1. Numbers below 2 are not prime.
  2. Try dividing by every number from 2 up to the square root; any exact division means not prime.

Solution

Python
def is_prime(n):    if n < 2:        return False    for d in range(2, int(n ** 0.5) + 1):        if n % d == 0:            return False    return True for n in [29, 33, 1, 97]:    print(n, is_prime(n))
Output
29 True
33 False
1 False
97 True

Line by line

Lines 2-3

0, 1 and negative numbers are not prime.

Line 4

Checking up to √n is enough: if n had a factor larger than √n, it would also have one smaller than √n.

Lines 5-6

Return False as soon as a divisor is found.

Line 7

No divisor was found, so the number is prime.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Leave a Comment