I add new “elif” and it works)

thanks

I’ve tried a similar solutions for hours just to realize that 9 was retrieving True because the “else” statements was with the same indentation of the “if” why does it change the result so much?

Indentation matters so much because it shows python the order of operations in which to execute the code and also for `if/else`

statements indentation tells the interpreter what function or variable the if and else are checking.

i don’t understand how the code works,while x=2.can you explain it for me?if you are wiling to.

I tried many times but still fails !!!

def is_prime(x):

if x<2:

return False

elif x>2:

for n in range(2,x):

if x%(n-1)==0:

return True

else:

return False

elif x==2:

return True

else:

return False

How to solve it !!!

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

Try this. Should work.

Finally it works, Thanks for help,

but could you explain this line, cuz I don’t understand it

if n + 1 == x:

return True

Let’s take the `is_prime()`

function without `if n + 1 == x:`

statement.

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

If we take x = 9 and run it through the above function, it will return `True`

even though 9 is not a prime number. Because when ‘n’ is having value of 2 the else block of the nested if statement (`if x % n == 0:`

) will be executed.

`9 % 2 == 1`

But we only need the function to return `True`

when the loop is running for the last time (which is ‘n’ having its final value. In the above example it’s 8).

You can check that ‘n’ is having its final value by using `if n + 1 == x:`

.

I’m not fluent in English so I’m sorry for my English. Hope you understand my explanation.

Thanks very much for help

Can you explain why the else statement have to be outside of the loop? I got the same idea but I put the else inside the for loop and it’s caused an error

Hi,

It was in one of the sections prior to this in the course “for else loop statements”

Hi everybody,

I was cheking the codes for this task and I figure that the best way is not to use looping (for or while) because it will not run for long numbers. The memory will not let.

Try this way and make a raw_input to use the function for big big numbers

def is_prime(x):

if x==1 or x==-1:

return False

elif x==2 or x==3 or x==5 or x==7:

return True

elif x%2==0 or x%3==0 or x%5==0 or x%7==0:

return False

else:

return True