Previous Lesson Current Lesson Next Lesson

Question 1

x = "123"

if x == "foo":
    print("Success")

You can set x to whatever you want. In this case, we will not output anything because x != "foo" (not equal).

Question 2

x = "car"

if x == "foo":
    print("Success")
elif x == "car":
    print("Okay")
elif len(x) == 3:
    print("Nice!")

Notice that we changed our value of x to "car" to illustrate how Python handles multiple conditional statements. This will output:

Okay

Note that even though len(x) == 3 is also True, Python evaluates these conditionals in order, and once one is True, it does not continue checking ones after it.

Question 3

x = "horse"

if x == "foo":
    print("Success")
elif x == "car":
    print("Okay")
elif len(x) == 3:
    print("Nice!")
else:
    print("Oops!")

Notice that we changed our value of x to "horse" to illustrate how Python handles the else keyword. This will output:

Oops!

This is because none of the conditionals before it (i.e. if and elif conditionals) are True, so Python ends up executing the code exclusively in the else block.

Question 4

x = "cow"

if x == "foo":
    print("Success")
elif x == "car":
    print("Okay")
elif len(x) == 3:
    print("Nice!")
else:
    print("Oops!")

if len(x) == 5:
    print("Cow")

Notice that we changed our value of x to "cow" in this case. This will output:

Nice!

Notice that we don’t print out "Cow" because the second if statement isn’t True in our case (the length is 3).

Question 5

x = "Mouse"

if x == "foo":
    print("Success")
elif x == "car":
    print("Okay")
elif len(x) == 3:
    print("Nice!")
else:
    print("Oops!")

if len(x) == 5:
    print("Cow")

This will output:

Oops!
Cow

In the first if-else block, none of the statements are True, so the only thing that will get executed is the print statement under the else block. The print statement under the second if statement also gets executed because its conditional is also True.

Remember, once one of the conditionals is True, Python will stop checking any subsequent conditionals until it encounters another if statement, in which case it resumes checking in the top-to-bottom fashion described in the lesson.