We can use both
method to call the next value in the sequence. The
method makes the generator function run until it reaches the next yield value. So this is what happens:
1) We define
2) We use
which calls the generator function.
countdown prints the
print statement, and enters the
while loop. On encountering the
sign, it returns the value of
num, thereby stopping further execution of the
4) Once the value is returned, we move forward by calling the generator function again with
countdown returns to the function where it last stopped the execution. It decreases the value of
by 1 and continues the
loop by entering it again.
6) Everything that follows from here is repeated(steps 2–5) until the condition in
7) Calling the generator function now, will return a
error, because there is nowhere to go now.
every time is tedious! So instead of that we use my favorite python loop
— I think is really powerful, for you can use it to iterate in a list of items, lines of a file, results of a generator function or any other object that supports iteration. So when you write
for i in s
can be any of the items that I mentioned above!
Before moving further, I’d like you to try out this command in your terminal:
(you will have to type
tail -f file_name | grep search_term
ctrl+c to stop the execution of the commands).
is used to print the last 10(default value) lines of a file and is often used to monitor log files, while
grep is used as a search tool, it prints lines matching the given search_term(pattern). (You can run
in your terminal to find out more about these commands.). When we use the
flag, it continuously monitors the given file, so as soon as you append a new line to the given file, it will print the appended sentence.
To make things interesting, lets write a python program to duplicate the behavior of these UNIX commands.
here is a generator that looks for a specific substring in a sequence of lines, while
generator reads lines from a given file and returns them to
command, as I said before, prints last 10 sentences of a file, but I was unable to duplicate that behavior, instead
generator here, will scan the whole file.)
References:  Python Essential Reference 4th Edition (2009),  Function Vs. Generators in Python