6. Is_prime

#1

The code returns the correct value on every value of x except for x = 9.
I get:
Oops, try again. Your function fails on is_prime(9). It returns True when it should return False.

the function works correctly for all other values. Prime numbers like 2, 5 or 11 or 521 return True like they should and non prime numbers like 4 or 18 return False like they should. It is just 9 That doesn't work for as far as I can tell.

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

#2

``````else:
return True``````

Properly indent it!

hint**
use of `for/else`..

#3

that the numbers you picked work is sheer luck to be honest, sorry

The problem is in your for loop, lets first get one sorted:

a function ends the moment a return keyword is reached

If a return keyword is reached in a loop, the function still needs to end, so the loop will break in order for the function to be able to end

We can use this to our advantage, we can have a loop, which returns False when the remainder of the division equals zero, causing the loop and function to end. Perfect, no unnecessary loop iterations after we determined the number is not a prime number

But a number is only a prime number when the loop finishes running, so we only want to return True after the for loop has finished running

Currently, in your program, True or False is returned based on the fact of the first division has a remainder of zero

This is why i said, the numbers you picked is sheer luck that they turned out correctly

#4

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