I found this code to generate prime number in Python3:
def gen_primes(N):
"""Generate primes up to N"""
primes = set()
for n in range(2, N):
if all(n % p > 0 for p in primes):
primes.add(n)
yield n
Here I have confusion with the line if all(n % p > 0 for p in primes)
. Since primes
is initially blank, so the code inside "if" should never execute.
To become confident, I tried the code below and it is not executing the code inside the "for".
primes = set()
n=2
print("---------Outside For Loop--------")
for p in primes:
print("---------Inside For Loop------")
if all(n%p>0):
print("Hello")
else:
print("No Way")
So I need expert help here to understand how this prime number generator working in this case?