An if statement’s block can contain any Python statement, which implies that it can include other if statements. An if statement inside another is called a nested if statement.
| | value = input('Enter the pH level: ') |
| | if len(value) > 0: |
| | ph = float(value) |
| | if ph < 7.0: |
| | print(ph, "is acidic.") |
| | elif ph > 7.0: |
| | print(ph, "is basic.") |
| | else: |
| | print(ph, "is neutral.") |
| | else: |
| | print("No pH value was given!") |
In this case, you ask the user to provide a pH value, which you’ll initially receive as a string. The first, or outer, if statement checks whether the user typed something, which determines whether you examine the value of pH with the inner if statement. (If the user didn’t enter a number, then the function call float(value) will produce a ValueError.)
Nested if statements are sometimes necessary, but they can get complicated. To describe when a statement is executed, you have to combine conditions mentally; for example, the statement print(ph, "is acidic.") is executed only if the length of the string that value refers to is greater than 0 and pH < 7.0 also evaluates to True (assuming the user entered a number).