Python 3 latest code crumbs

Demonstration of how a Python range works

Demonstration of how a Python range works

Mar 6, 2022 by erik

A range is an iterable object, and this object can return an iterator that keeps track of its current state. Suppose we create a range with the call range(3). This returns an object of type range with our requested settings....

range iterators
Python for-loop using range with start and stop

Python for-loop using range with start and stop

Mar 6, 2022 by erik

We don't always want to start counting at zero, and that's why we can also call range with both a start and stop value. A call to range(2, 5) will return the values 2, 3, and 4....

range for-loop
Python for-loop with range (with one argument)

Python for-loop with range (with one argument)

Mar 6, 2022 by erik

If we call Python's range with one argument, that argument is the stop value. In this case, range will start counting at 0 until it reaches the stop value. For example, if we call range(5), the created range object will...

Creating a Python iterator

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....

iterators classes
Python ZeroDivisionError: Handling Division By Zero

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....

exceptions
Convert YAML to JSON using Python

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...

yaml json trick