The issue you have is that your loop prints out something on every iteration. You can't do that if you only want to print that n
is prime when you're sure it is. You can only be sure of that when your whole loop completes.
This is easiest in a function, where you can return
whenever you have a firm answer:
def prime_check(n):
for i in range(2, n):
if n % i == 0:
return False
return True # this only runs after the whole loop ends
n = int(input("enter a number\n"))
if prime_check(n):
print(f"{n} is prime")
else:
print(f"{n} is not prime")
If you want to keep the check inline, rather than using a function, you can do that too, with some clever use of break
and the else
clause attached to the loop, rather than the if
. Such a clause only runs if the loop exits normally, not if it's exited early by a break
statement. This can be a bit confusing, which is why I put it second, after the return
version that is a lot more clear.
n = int(input("enter a number\n"))
for i in range(2, n):
if n % i == 0:
print(f"{n} is not prime")
break
else: # the else is attached to the for loop now, not the if
print(f"{n} is prime") # this line is only runs if no break happened in the loop