Your code has some issues. To start with, you're never updating a
, so you only ever check if the number n
is even.
Once you fix that, you have two indentation problems. The first is that the break
line needs to be inside the body of the if
statement. Indent it more so that it's inside the if
block.
The second indentation issue is more subtle. If you leave the else
where it is, it will print out that the number is prime every time you test a potential factor that doesn't divide the number. That's both unhelpful (since it prints a lot) and wrong (since it says the number is prime even if it will later find a factor and say it's not prime). You can fix this by unindenting the else
line so that it is lined up with the while
statement. Using an else
after a loop is an obscure bit of Python syntax. The body of the else
only runs if the condition of the loop fails. It gets skipped if the loop exits due to a break
statement.
Here's all of those necessary fixes together:
while n > a:
if ((n % a) == 0) & (a != n):
print('Sorry, the number you have entered is not prime.')
break # indent this line more!
a += 1 # increment a, so you don't keep checking 2 over and over
else: # unindent this line (and the next line too)
print('The number you have entered is indeed prime!')
There are some other things that could be improved in your code, though they aren't causing it to run incorrectly. I'd recommend using int
instead of eval
to parse your number, and I'd use the logical-and operator and
instead of the bitwise-and operator &
in the if
statement (though actually you don't need either, since the a != n
check is redundant, as the loop would have already ended if it was true).