I’ve been trying to get this code to work to return a input number as prime between 2 and 49, but all it does is return most numbers as prime, even when they aren’t… For the exercise, I was given that 3, 5 and 7 were prime anyway, so just ignore that bit…
def prime(a):
if a < 2: return False
if a % 2 == 0: return False
if a == 3 or a == 5 or a == 7: return True
for n in range(3,int(a ** 0.5) + 1):
if a % n == 0: return False
if a % n != 0: return True
a = input("Enter a number between 1 and 49: ")
if prime(a) is False:
print a, " is not a prime number"
if prime(a) is True:
print a, " is a prime number"
You don’t need that 2nd if condition. else it will immediately return when the number is not divisible by current value of
n. But you don’t want that. You need to check for the next value if the currentncannot divide your number.So, just remove that if, and add a
return Trueafter the loop ends..So, your
prime()method should be like this: –