# 6. is_prime

#1

The error message I get: Oops, try again. Your function fails on is_prime(9). It returns True when it should return False.

From all I understand so far, this should iterate trough a list of integers (to index of x, which is one less than x), use them to divide the x by, and report False as soon as modulo gives a zero (indicating that x is divisible by one of the n). I must be missing something. Please help.

``````def is_prime(x):
x = abs(int(x))
if x < 2:
return False
elif x >= 2 and x <= 3:
return True
else:
for n in range(2,x):
while x % n != 0:
return True
else:
return False``````

#2

That logic needs a rethink. A `return` in a loop will exit the function on the first iteration. Can you think of some other way to work this so it does not use `while`?

#3

Try looking over this code and review the steps being taken to get the desired solution.
- First you want to check if the number is less than 2 and if so return false. If not go to the next step.
- Once the first step is passed create a for loop to run the numbers between 2 and the input(x) checking if x is equally divisible by "n". If this is true the loop will print out false. If the first statement is false the loop will move to its else statement by returning True

``````def is_prime(x):
#if x is less than 2 return false if not continue with next step
if x < 2:
return False
else:
'''check if x is divisible evenly by "n"
and if so return false. If not return true'''
for n in range(2, x - 1):
if x % n == 0:
return False
else:
return True``````

#4

Thank you for the help!

#5

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