My code breaks for is_prime(4). Any idea why?

def is_prime(x):
result = True
if x < 2:
return False
elif x ==2:
return True
for n in [2,x-1]:
if x%n =='0':
result = False
result = result and True
return result

Preformatted text


lets start on line 8:

for n in [2,x-1]:

this will create a list with two values, while you need all values between 2 (included) and x (excluded), maybe you can use range for this?

you only want result to be true after the for loop has finished running, so place else outside the for loop. After you made this changes, post an updated version of your code, so we can help you further


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