Control flow
Contents
1.3. Control flow#
1.3.1. 5 use-cases of ternary operators#
Ternary operators are one of the best one-liner tricks in Python. When used correctly, it will make your code much more readable and compact.
Here are 5 use-cases of them👇
1.3.2. Conditionals replaced by dictionaries#
You can greatly simplify your conditional statements by using dictionaries.
Of course this approach has its drawbacks, but I have used it to great effect in a project where I collapsed a nested conditional block over 100 lines into just a dozen.
1.3.3. Python for/else clause#
Did you know that for loops in Python has an “else” clause?
An else in a for loop is executed as soon as a loop finishes or encounters a break statement. In the second snippet below, you can see an example usage from the Python docs. Pretty neat, huh?
1.3.4. Conditional looping with filterfalse
of itertools
#
How to perform conditional looping in Python without using “if” statements? By using the “filterfalse” function.
“filterfalse” accepts a boolean function (usually a lambda) that tells which elements should be discarded during the loop. For example, in the below example we are skipping numbers that are divisibly by three.
In other words, we are only keeping the values that return “False” to the condition inside the looping function.