# 6. is_prime

#1

Define a function called isprime that takes a number x as input._
For each number n from 2 to x - 1, test if x is evenly divisible by n.
If it is, return False.
If none of them are, then return True.

Code:

``````def is_prime(x):
result = 0
for n in range(2, x-1):
if x % n == 0:
return False
else:
return True``````

Oops, try again. Your function fails on is_prime(0). It returns None when it should return False.

#2

The loop should not contain an else clause. Let the loop complete then return True.

#3

Sorry, obviously conditions.

``````def is_prime(x):
result = 0
if x < 2:
return False
elif x > 2:
for n in range(2, x-1):
if x % n == 0:
return False
else:
return True``````

Oops, try again. Your function fails on is_prime(2). It returns None when it should return True.

#4

To reiterate, no else clause in the `if`, and no return True in the loop.

#5

You won't believe.

I just delete "else" condition and change indentation

``````def is_prime(x):
result = 0
if x < 2:
return False
elif x > 2:
for n in range(2, x-1):
if x % n == 0:
return False
return True``````

and this worked. But one problem - I don't understand why.

Why return out of "if x % n ==0" condition?

There's no left operations, when we search modulo for input number x

#6

Because it is evidence of divisibility, which means the number is not a prime. If the loop completes without kicking any number out, then flow gets to the final line.

#7

Thank You! Looks like I miss some basic knowledge.

#8

That is where writing prseudo code comes in to the design process. Design the flow before setting out any code. Once the roadmap is in place, code to suit, test, refit, refine, refactor, and test some more against a range of inputs. Soon you have a number of fairly common roadmaps in your head and code falls into place quickly as you progress.

#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.