LearnFrenzy
Sign in Take a free test

Functions · Functions Coding Problems · Question 1

Prime number checker function in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Write is_prime(n) and use it to list the primes between 1 and 40 and to test a few large numbers.

Solution
main.py Run
def is_prime(n):
    """Return True if n is a prime number."""
    if n < 2:
        return False
    if n % 2 == 0:
        return n == 2
    d = 3
    while d * d <= n:
        if n % d == 0:
            return False
        d += 2
    return True

print([n for n in range(1, 41) if is_prime(n)])
print(is_prime(7919), is_prime(7917))

Output Verified by running it on Python 3

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
True False

Even numbers are handled once; only odd divisors up to √n are tried. Early returns keep the function flat.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links