Is Prime


Hello! Stuck on x as 9 with the below code. Can anyone help?

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


You do not need a break statement, neither do you require an else block,

1. Remove the break statement

  1. Remove the else: statement,
  1. Put the return statement of the else block on the same indentation level as the for loops,

for n in range (2,x):
    if (x % n) == 0:
       return False
return True

After correcting those errors your code should work just fine. :grin:


Thank you kind sir!

I am struggling to understand why the return True on the last line only works outside the loop however. Could you shed any light?


Because this is sort of like the else: block of your loop meaning if it loops from 2 to your number and divides your number by the for loop variable it will return False, otherwise it will return True


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