There is a lot difference!
The first one is wrong!:
def if_prime(num):
for divisor in range(2,num):
if (num % divisor) == 0:
return f"{num} is not prime"
else:
return f"{num} is prime"
This checks whether a number has any factor between 0 and num and if it finds a factor it returns saying that the number is not prime.
But the mistake is that if it does not find a factor then it returns true at once and does not check for other divisors:
For example this will say that 9 is a prime number is it is not divisible by 2 and the if condition becomes false!
On the other hand the second one is correct! :
def if_prime(num):
for divisor in range(2,num):
if (num % divisor) == 0:
return f"{num} is not prime"
return f"{num} is prime"
In this one too we loop through all the divisors from 2 to num but in this case we do not return anything if one number is not a divisor( we check through all the possible divisors ) thus if the loop ends and we find no divisor then it means it is a prime number!
But this too has a small bug as it will say 1 is a prime number!
Here is a proper and efficient version of the if_prime function:
def if_prime(num):
for divisor in range(2, num/2):
if (num % divisor) == 0:
return f"{num} is not prime"
if num == 1:
return f"{num} is not prime"
else:
return f"{num} is prime"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…