Generators can also be used to make a very optimised program that outputs prime numbers.

The program can be downloaded at:

https://www.dropbox.com/s/cberpasioaco733/primes.py

Here if the program is run by simply calling it:

$ python primes.py 5

[1, 2, 3, 5, 7]

Running the script again does not resume it, but starts a fresh run of the program and the same 5 primes are generated. This is because Python program is re-launched and it has no memory where the previous program paused.

$ python primes.py 5

[1, 2, 3, 5, 7]

However running a Python Interactive Shell, can help generate primes continuously (or by calling this script from another program)

>>> import primes

>>> g = primes.generate()

>>> [g.next() for i in range(10)]

[1, 2, 3, 5, 7, 11, 13, 17, 19, 23]

>>> [g.next() for i in range(10)]

[29, 31, 37, 41, 43, 47, 53, 59, 61, 67]

### Like this:

Like Loading...

*Related*