In short: the if fires when n is dividable by x.
Background:
If you write something with:
if <expr>:
pass
The not keyword also evaluates the truthiness, and in case the truthiness is True of the expression, then not expression is False and vice versa.
Python checks the truthiness of the <expr>. The truthiness is a boolean value that is associated with objects.
True and False have as truthiness respectively True and False, and None has truthiness False (so we can check if someobject usually to do an implicit None check).
Collections like lists, sets, dicts, tuples, etc. usually have truthiness True if and only if these collections contain at least one element. So empty collections have truthiness False. What these collections contain is of no importance for the truthiness of the collection itself.
Then there are also numerical types. Usually a number has truthiness False if and only if it is equal to zero, so negative and strictly positive numbers have truthiness True.
Generic objects have by default truthiness True, but you can override the __bool__ magic function to return a different truthiness, or if you override __len__ (and not __bool__), it will check if __len__ is greater than zero.
So if n and x are integers, then we calculate n % x, this thus performs a modulo check, and n % x is zero if and only if n is dividable by x.
Now the not operator will thus evaluate the truthiness. In case n is dividable by x, then not n % x is True, otherwise not n % x is False.
So the if is fired if n is dividable by x. The prime test thus checks if n is dividable by all numbers between 2 and n/2+1, and if not, it returns True, from the moment one is dividable, it returns False.
We can however speed up the calculations by iterating up to the square root of n, and make hops of two:
from math import sqrt
def IsPrime(n):
if not n % 2:
return False
for x in range(3, int(sqrt(n)), 2):
if not n % x:
return False
return True
bool(6)andbool(0)in the Python shell