4.5. Nested Conditionals¶
In addition to chaining, you can also nest one conditional within another. We could have written the previous example as:
This program classifies a number (x) as positive, negative, or zero, just like the program on the previous page. However, this time, we are using nested conditionals.
There is now an outer conditional that contains two branches. The first branch contains a simple output statement, but the second branch contains another if statement, which has two branches of its own. Fortunately, those two branches are both output statements, although they could have been conditional statements as well.
There is not a limit to the number of times you can nest a conditional. However, you should try to limit this number, as it will reduce the complexity of your program structure.
Notice again that indentation helps make the structure apparent, but nevertheless, nested conditionals get difficult to read very quickly. In general, it is a good idea to avoid them when you can.
On the other hand, this kind of nested structure is common, and we will see it again, so you better get used to it.