def is_prime(x):
if x < 2:
return False
elif x == 2:
return True

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

Guys i dont fully understand what the second half of the code does (for n in range ....)
can someone please explain. Thanks really appreciated.


It takes a range from 2 to one less than x. If x is 12 then the range would be: (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)



@cadecodes is correct, but if you want to improve your prime checker you can implement some math concepts to your code.

Such as

  • Checking if the number is divisible by x, generally 2 before brute forcing it
  • Only checking up to the square root of your number
  • If you checked if divisible by two, only check if odd numbers divide your number to reduce the amount of work needed to be done.

It is actually a good exercise to create a script that can do this as it will teach you a few more things and not just about Python.