I recently started coding and encountered something I didn't understand fully while trying to learn Python on Codecademy.
The task was to create a function that would tell if called upon, whether the number was a prime number or wasn't.
So here was my first solution:
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range(2, x-1):
if x % n == 0:
return False
else:
return True
print is_prime(5)
After running it, it kept giving the message that is_prime(3) was giving False, instead of giving a True. So after searching a little bit on the Codecademy forums I found that if the last bit of the code was alterd to:
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range(2, x-1):
if x % n == 0:
return False
return True
print is_prime(5)
it started working normally. Could anyone explain me how this alteration caused the code to work? Thanks in advance.
is_prime(3)would return eitherTrueorFalsefor the first version, asrange(2, 3-1)is empty and thus the code never gets a chance to return anything other than the defaultNone.Noneas false-y