Watching:

Create sequences with generator functions Python 3


show more Creating sequences with generator functions provides you with in-depth training on Developer. Taught by Bill Weinman as part of the Python 3 Essential Training show less
please wait ...

Creating sequences with generator functions

Generator functions are an incredibly useful pattern in Python. What a generator function does is it actually creates an iterator. Let's take a look at how this works. We can make a working copy of generator.py. I'm going to call it generator-working.py. Go ahead and open that up and take a look. This is the generator here. Now it calls this isprime, which is very similar to the one that we used in our functions example, except instead of the Print statements, it returns False if it's not prime, and it returns True if it is prime. So that's a little utility function.

This one here, it looks, at first glance, like a normal function, and in fact, it is, except it has this yield statement. Yield is like return. It returns a value. You see here we have return False, return True. Those return those Boolean values. This one here returns a number, and it returns this number only if isprime returns true, so it returns the next prime number, but it uses yield instead of return.

And what yield does is it returns a value, but then the next time the function is called, it continues execution after the yield. So in this case, we have this while loop. And it checks to see if the number is prime. If it's not, it increments and checks the next one. And if it is, it yields. And that will return a value. And then the next time this function is called, it'll just continue here, incrementing and looking for the next one. And so this actually, because of these of yield, it returns an iterator object, that is suitable for use in a for loop.

And here we have a for loop, and for n in primes, and so it calls this primes function. There is the primes function. And for each iteration, it'll put the value in n. And it'll print it out, and it tests to see if it's greater than 100. Then it breaks out of the loop. And so this uses this generator function as an iterator. And it will print a list of prime numbers. Let's go ahead and take a look at this as it works. We'll run it.

And here we have a complete list of all the prime numbers up to 97. So you can see that this is incredibly useful. And we'll some more examples of it as we go through the course. So this is a generator function, and what it generates is an iterator that's suitable for use in a for loop, just like any iterator in the Python language.

Creating sequences with generator functions
Video duration: 2m 46s 6h 36m Beginner

Viewers:

Creating sequences with generator functions provides you with in-depth training on Developer. Taught by Bill Weinman as part of the Python 3 Essential Training

Subjects:
Developer Web
Software:
Python
Author:
please wait ...