Developer advocate / Data Scientist - support open-source and building the community.
Python Zero to Heros
Online Absolute Beginner Python Tutorials
Every Sunday 2pm (UK time/ BST)
Get this slide deck:
Python objects - int, float, str, list, dict, bool
Control flows - if-else, for loop, while loop
Functions, modeuls, classes and decorators
strings operations and regex with re
pytest with fixtures and mock
python linters & auto-formatters
What is Generator?
Generator functions allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.
Python generators are a simple way of creating iterators.
Compare to implement a class with __iter__() and __next__() method.
def firstn(n): num = 0 while num < n: yield num num += 1
Differences between Generator function and Normal function
- Generator function contains one or more yield statements.
- When called, it returns an object (iterator) but does not start execution immediately.
- Methods like __iter__() and __next__() are implemented automatically. So we can iterate through the items using next().
- Once the function yields, the function is paused and the control is transferred to the caller.
- Local variables and their states are remembered between successive calls.
- Finally, when the function terminates, StopIteration is raised automatically on further calls.
Sending to generator
The send() method resumes the generator and sends a value that will be used to continue with the next yield. The method returns the new value yielded by the generator.
def numberGenerator(n): number = yield while number < n: number = yield number number += 1 g = numberGenerator(10) # Create our generator next(g) # print(g.send(5))
Python 3.3+ : yield from
def generator1(): for item in generator2(): yield item
def generator1(): yield from generator2()
Sunday 2pm (UK time/ BST)
This week no Mid Meet Py because:
By Cheuk Ting Ho