Feb-02-2022, 07:07 PM
(This post was last modified: Feb-02-2022, 07:07 PM by deanhystad.)
Quote: Anyway whats the point of having a function if you need an if statement to stop the generator.First off, it is a generator, not a function. Functions return a value and they are done. Generators return a value and hold.
The point of a generator like this is you may not always know when a sequence should end. Lets say I want a sequence of prime numbers that add up to 100 or less. I don't know when my sequence should stop exactly. I can guess, but I don't know. I could write it like this:
primes = [] total = 0 for p in prime_numbers(): if (total := total + p) > 100: break else: primes.append(p) print(sum(primes), primes)
Output:100 [2, 3, 5, 7, 11, 13, 17, 19, 23]
Or if you prefer a while loop.primes = [] total = 0 prime_gen = prime_numbers() while total < 100: p = next(prime_gen) if (total := total + p) <= 100: primes.append(p) print(sum(primes), primes)My example is a bit hokey, but so is the prime_numbers() generator in your example. I think this code is supposed to demonstrate using a generator and is not meant to be used as a prime number generator.
I agree that there is probably a little language barrier here. Some of your questions are a bit awkward, but I am only proficient in one language, so you are way ahead of me. This is far from "conversational English" and many native English speakers have trouble asking questions on this forum.