top of page

# Summary

### Nested If

If Statements can be stacked one after another as you have seen in previous examples, but it is also possible for If Statements to be nested within a parent If Statement. Let's look at an example below:

1  operation = "division"

2  number1 = 9

3  number2 = 3

4  if operator == "division":

5      if number2 == 0:

6          print("You cannot divide by zero")

7      else:

8          print(number1 / number2)

9  elif operator == "multiplication":

10     print(number1 * number2)

The first If Statement checks to determine if the operation is division. If so, then there is a secondary check to determine if the denominator (number2 in this case) is zero.

â€‹

Now let's have you try. Let's complete this calculator by adding addition and subtraction. But our calculator has two special requirements:

• The two variables (number1 and number 2) should always be positive

• The result of any calculation should never be less than zero (HINT: watch out for subtraction)

â€‹

If either of these rules are violated, the calculator should print: "This operation is not allowed"

bottom of page