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.

Note

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.

Too many nested conditionals is considered a bad practice.

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, so it is important to be able read nested code, regardless of whether it is a best practice or not.


More to Explore

You have attempted of activities on this page