Here’s a simple example of using an if-statement inside another if-statement:
Notice that the second if-statement is part of the block associated with the first if-statement (indented). The line print("Would you like a cookie?") is indented again because it is associated with the second if-statement. As a result, if last_name has the value "Monster" and first_name has the value "Cookie," then both print() statements will be executed when the program is run. On the other hand, if last_name has the value "Monster" and first_name has some value other than "Cookie," then the program executes the first print() statement ("Welcome home, Mr. Monster."), but the second will not.
So what happens if last_name isn’t set to "Monster," but first_name is set to "Cookie"? In such a case, the program will execute neither print() statement. Recall the behaviour of an if-statement: if the if statement's condition is False, then the entire block associated with the if-statement is skipped over. Since the second if-statement is part of the block that is being ignored, its associated condition happens to be True is irrelevant; the computer won’t even check. When we combine nested if-statements with else (or elif) statements, paying attention to indentation becomes very important. Consider the following two programs:
The programs are identical except for the indentation of the else statement and its associated block. For listing 13.1, the program will declare a burglar whenever last_name is not equal to "Monster," regardless of the value of first_name. That’s because the else is at the same level of indentation as the first if-statement, indicating that the else is associated with the first if-statement. In listing 13.2, the else is associated (via indentation) with the second if-statement. Thus, the program outlined in 13.2 will only report a burglar when last_name is equal to "Monster," but first_name is not equal to "Cookie." If last_name is not equal to "Monster", then the program won’t print anything to the screen.