top of page

If Operations

Checkpoint #1



Checkpoint #2

Nested If



You might have noticed that statements under the conditional are all indented. This is actually critical to the format of code in Python. See what happens when we don't include the whitespace:

1 handedness = "right"

2 if handedness == "left": # Equal to

3 print("You are left-handed")

Notice that the error says "expected an indented block." In this case, Python is actually giving a very informative error message, because that is exactly the problem. Also note that the colon : is a critical part of the syntax of the if statement!

Whenever we have a conditional statement (if or else), the command executed below it must be indented. This tells Python which commands are dependent on the if statement and which are not.

Let's try another example. Can you fix the following code so that the output is "I have an apple!"

1 myFruit = "apple"

2 if myFruit == "orange":

3     print("I have an orange")

4 if myFruit == "grapefruit":

5 print("I have a grapefruit")

6 if myFruit == "apple":

7     print("I have an apple")

8 if myFruit == "banana":

9 print("I have a banana")

bottom of page