Chapter 3: If statements

Test your understanding

face Josiah Wang

Here are some questions to test your understanding of nested if-else statements and multi-way selection (if-elif-else) statements.

1 2 3 4 5

Question 1

What does the following code snippet output? Type Blank if the code does not output anything, and Error if it produces an error.

coins = 5
if coins < 2:
    coins = coins + 3
elif coins <= 5:
    coins = coins + 2
else:
    coins = coins + 1
print(coins)
7
Explanation:

The elif condition is fulfilled. The program adds 2 to the value of coins, making it 7. Note that the else clause is NOT executed since the elif clause has already been fulfilled.

Question 2

What does the following code snippet output? Type Blank if the code does not output anything, and Error if it produces an error.

coins = 5
if coins < 2:
    coins = coins + 2
elif coins < 5:
    coins = coins + 1
print(coins)
5
Explanation:

You are allowed to leave out the else. If this case, both if and elif conditions are not fulfilled. The value of coins remains at 5.

Question 3

What does the following code snippet output? Type Blank if the code does not output anything, and Error if it produces an error.

coins = 5
elif coins < 4:
    coins = coins + 2
else:
    coins = coins + 1
print(coins)
Error
Explanation:

You cannot have an elif or else without an if clause.

Question 4

What does the following code snippet output? Type Blank if the code does not output anything, and Error if it produces an error. If the output consists of multiple lines, enter the output of each line in a separate line.

student_count = 10
if student_count < 10:
    print("Small group")
else:
    if student_count < 20:
        print("Medium group")
    else:
        if student_count < 100:
            print("Large group")
        else:
            print("Overly large group") 
Medium group

Question 5

Did you find the previous code difficult to read? This often happens when you nest your code too deep. Try rewriting the code below to use if-elif-else instead. Is it easier to read now?

student_count = 10
if student_count < 10:
    print("Small group")
else:
    if student_count < 20:
        print("Medium group")
    else:
        if student_count < 100:
            print("Large group")
        else:
            print("Overly large group") 
Sample solution:

A possible solution:

student_count = 10
if student_count < 10:
    print("Small group")
elif student_count < 20:
    print("Medium group")
elif student_count < 100:
    print("Large group")
else:
    print("Overly large group")