The nesting of a conditional statement works by writing an “If-else” inside another “if-else”, this way we can apply multiple conditions to a single value, having something similar to a filter with multiple layers.

This is an important tool, but you should be very careful when writing a nested condition, since this can get very confusing if you lack order with our thoughts and your programming style.

You have to be very careful with the indentation you use when writing the conditionals, or else the program will fail.

The following is an example of a nested conditional:

v = 100

if v < 200:

print “Expression value is less than 200”

if v == 150:

print “Which is 150”

elif v == 100:

print “Which is 100”

elif v == 50:

print “Which is 50”

elif v < 50:

print “Expression value is less than 50”

else:

print “Could not find true expression”

It I useful to imagine ifs as tree diagrams, every time you get to a road-split you have a certain amount of options to follow and you have to choose one to advance forwards, and the way of visualizing a nested conditional is a crossroad that leads to another crossroad.

This gives you a whole new world of possibilities for filtering and processing data, but you have to be careful, the more intricate the nesting is the more you will have to debug and the harder it will be, so be careful and ONLY use nesting when absolutely necessary.

CC BY 4.0 Nesting of conditional statements by juansalvadorfernandez is licensed under a Creative Commons Attribution 4.0 International License.