As the first thing, you should remember that 1
isn't a prime number by definition, even if it can't be divided by any other number:
if (num == 1):
print("The number is NOT prime")
else:
for i in range(2, num):
if (num%i == 0): # If the number has a divisor
print("The number is NOT prime")
break
else: # If the for loop ends without reaching any break
print("The number IS prime")
The else
branch of a for
loop is reached when the loop ends without reaching any break
AND the loop executes at least one time.
To better understand my answer, I would suggest to read this.
The error with your solution is caused by the loop printing that the number is prime for each time num%i == 0
, so taking num = 6
:
6%4 != 0 # The number is prime
6%5 != 0 # The number is prime
As Rajarshi Ghosh
suggested, you should know that while programming it's a good idea to use import
ed functions to do this simple operations, in order to avoid long operations for such a simple job.
If you don't want to use an imported function, I would suggest you to read this article where they explained 6 ways of finding if a number is prime without using functions made by others.