def all_primes(start,end):
list_nonprimes = []
list_primes = []
for i in range(start,end):
for a in range(2,i):
if i % a == 1 and i not in list_nonprimes:
if i not in list_primes:
list_primes.append(i)
else:
list_nonprimes.append(i)
return list_primes
Why is this giving me an an incorrect output?
>>> all_primes(1,10)
[3,5,7,9]
How do I eliminate the 9?
There’s a more straightforward way to do this, since you’re already inherently generating the list of primes less than the number you’re currently checking:
Key to understanding this is knowing how the
for...elseconstruct works in Python. Essentially, aforloop can have anelsestatement, which is only executed if nobreakstatement was run during the evaluation of the loop.