4.6. Nested conditionals¶
One conditional can also be nested within another. We could have written the three-branch example like this:
The outer conditional contains two branches. The first branch contains a
simple statement. The second branch contains another
statement, which has two branches of its own. Those two branches are
both simple statements, although they could have been conditional
statements as well.
Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. In general, it is a good idea to avoid them when you can.
Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional: