-2

I wrote the code below to check for prime numbers but when I run the code both the if and else statements execute the same output.

n = int(input("enter a number\n"))
for i in range(2, n):
    if n % i == 0:
        print(f"{n} is not prime")
    else:
        print(f"{n} is prime")
Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • 2
    Does this answer your question? [Prime number check Python](https://stackoverflow.com/questions/10666154/prime-number-check-python) – Michael M. Aug 10 '22 at 19:16
  • 1
    pick a number in your head and walk through your algorithm. what will get printed if you enter 5? 6? 7? – Michael Delgado Aug 10 '22 at 19:19
  • [n := int(input("enter a number\n"))] for i in range(1, n): if n % 2 == 0: print(f"{n} is not prime") else: print(f"{n} is prime") – toyota Supra Aug 10 '22 at 19:43

2 Answers2

0

Sympy.isprime is probably the most efficient way unless you want to check various numbers. In that case, it's better to use the Sieve of Eratosthenes.

If you do not want to use modules or semi-complicated algorithms, the following plain code works perfectly if you need to check just a few numbers smaller than 10**6.

def isprime(num):
    for n in range(2,int(num**0.5)+1): 
        if num%n==0:
            return False
    return True
Jock
  • 388
  • 2
  • 12
0

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
Blckknght
  • 100,903
  • 11
  • 120
  • 169