I wrote a prime number generator:

def primes(): prime = True i = 1 while True: i += 1 for j in range(2, i): if i % j == 0: prime = False if prime: yield i else: prime = True 

But something I do not understand how to use it. I do as a challenge:

 x = primes() print(x) 

Displays an object, not a number.

In the case of such a call print(next(primes())) all the time I get 2 on the output.

How to use generators?

2 answers 2

 def primes(): prime = True i = 1 while True: i += 1 for j in range(2, i): if i % j == 0: prime = False if prime: yield i else: prime = True 

Print all prime numbers not more than 100
http://ideone.com/wiVXOE

 for p in primes(): if p > 100: break print(p) 

Print the first 7 prime numbers:
http://ideone.com/sYrLpA

 p = primes() for i in range(7): print(next(p)) 
  • And besides for there are ways? - faoxis
  • @faoxis, sorry, I don’t know a python at all. I believe that any functions that are lazily working with iterators will do. But the answer added a little. - Qwertiy
  • @faoxis you get a generator when you call, for example. a = primes() . To get the next value now, call a.next () several times. In general, read about the generators. In general, the answer is correct - FeroxTL
  • @faoxis, a typical way to use an iterator is to walk through it using for or pass to a function. next in everyday practice is rarely used. - insolor

print (next (primes ())) does not work the way you want, because each time you call primes () it will return a new generator object, and for each of them the next will work once and take only the first value.

You need to first fix one generator object in a variable, and only then do next for it.

 p = primes() print(next(p)) # Выведет 2 print(next(p)) # Выведет 3 print(next(p)) # Выведет 5