Search⌘ K
AI Features

Solution Review: Check Whether a Number is Prime

Explore how to create a Python function that determines whether a number is prime. Understand the use of conditional checks and loops to validate if a number is divisible only by one and itself.

We'll cover the following...

Solution

Python 3.5
def is_prime(n):
"""Tests if a number n is prime."""
if n <= 1: # Adding this condition
return False
divisor = 2
while divisor <= n // divisor:
if n % divisor == 0:
return False
divisor += 1
return True
n = 1
print(is_prime(n))

Explanation

Over here, we have to add in the condition for when n is less than or equal to 1, as you can see in line 3 of the above code. If n is either less than or equal ...