13.0 Nesting Programming Constructs

So far, we’ve learned about two types of control statements: conditionals (involving the keywords if, elif and else) and loops (involving the keywords while and for). These types of control statements have the same basic structure: the control statement appears first, followed by an indented block of code. The block of code below the control statement consists of one or more valid Python statements. There are no restrictions on the sorts of statements that can go in the block, so naturally, the block can include additional control statements. Thus, we can have if-statements inside loops and loops inside if-statements in any combination you can imagine. This concept of including control statements within control statements is known as nesting.

In this chapter, we’re not going to present any new information. Instead, we'll just look at several examples of programs that combine conditionals and loops in different ways.