The problem with this code …
if x < 2:
elif x == 2:
for n in range(2, x):
if x % n == 0:
… is that the
else structure that is inside the
for loop will
True as soon as an
n is found that does not divide evenly into
x. For example, in the case where
9, this happens when it is discovered that
2 does not divide evenly into that number. As a consequence,
9 is erroneously reported to be a prime number. This is because the loop does not have a chance to check
3 as a divisor, which does divide evenly into
9, and would prove that it is not prime.
In essence, the main issue is that we want the
for loop to be able to check all potential divisors before we report back that none could be found that divides evenly into the candidate number. An
else that matches a
for loop is appropriate for such an approach.
There may be a way to redesign the logic of the code so that you can have a final
else that aligns with an
if header instead of aligning with a
for loop, but that would likely involve code that is more complex than necessary.