Nesting of Conditional Statements

When we have nested conditionals we should look for a way to simplify them, remember the Zen of Python. So whenever you find yourself inside a horrible pyramid of five nested ifs, consider taking a look if you can simplify it, in the case you don’t well at least remember that 

Sparse is better than dense

So you may think how in the hell can you avoid having multiple nested ifs? Well the answer is boolean algebra.

Most of the time you compress several nested conditionals with just OR and ANDs operators. In Python the operators are simply the same words. Let’s take a look at that:

>>> if n>0:

         if m>0:

              print n+m

This is maybe a very simple example of what that means, but here we have two conditionals nested, that what they do is that if the number is positive and greater than zero then you print the sum of the numbers. 

Well this can be easily converted to:

>>>if n>0 and m>0:

       print n+m

And the result would be the same, cause instead of doing to steps of conditionals the conditional is checking the status of the logical operation of the “and”; wich will only be True when both conditions are met. So this way our code can be read  much more easily an it’s much more elegant.

This is my of my

CC BY 4.0 Nesting of Conditional Statements by Manuel Lepe is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.