Python 3 latest code crumbs
Creating a Python iterator
Mar 1, 2022 by erik
There’s no magic to creating your own iterator. I’ll demonstrate with a simple iterator class that returns even numbers. As we’ve learned, we need to implement __iter__
and __next__
. We’ll do this in one single class, to keep things simple....
Python ZeroDivisionError: Handling Division By Zero
Mar 1, 2022 by erik
As you hopefully know, we can't divide by the number zero. If we do so anyway, Python will throw an exception called ZeroDivisionError
, which is a subclass of ArithmeticError
. When can catch this exception with a Python try except block....
Convert YAML to JSON using Python
Feb 26, 2022 by erik
If you need to convert YAML to JSON, you can simply parse the YAML as we did above. In the next step, you can use the JSON module to convert the object to JSON. In this example, we open a...
Writing YAML to a file with Python
Feb 26, 2022 by erik
Although most will only read YAML as a configuration file, it can be very handy to write YAML as well. In the following example, we'll: * Create a list with names as we did before * Save the names to...
Python's Finally block In Try Except
Feb 20, 2022 by erik
The finally
block is executed regardless of whether an exception occurs or not. Finally blocks are useful, for example, when you want to close a file or a network connection regardless of what happens. After all, you want to clean...
Swap two variables in Python without using a third
Feb 15, 2022 by erik
With this neat little trick, you can swap two Python variables without using a third variable. Source: python.land blog...