Please explain an issue with python generator

Viewed 71

I'am currently studying Python and recently encountered Python generators. I think I'm getting the idea of it, but this code (a little function to yield prime numbers):

import math
def prime_num():
    num = 2
    while num < 20:
        sq = math.ceil(num**1/2)
        for i in range(2, sq+1):
            if num % i == 0:
                break
            else: 
                yield num
        num += 1
pr = prime_num()
for i in pr:
    print(i)

Outputs this:

3
5 
5 
7 
7 
7 
9 
11
11
11
11
11
13
13
13
13
13
13
15
17
17
17
17
17
17
17
19
19
19
19
19
19
19
19
19

Can somebody explain why are there multiple copies of a single int?

0 Answers
Related