Check your understanding of the previous reading: nesting, whitespace rules, and how elif compares to else with a nested if.

Question 1

Select the two snippets of code that are equivalent to each other.

Select every answer that applies, then check.

  • Not part of the equivalent pair. This is two separate, back-to-back if statements: both conditions are always checked, regardless of each other.
  • Correct. door_is_open() is only checked when is_on_fire() is false — exactly what the nested version on the right does.
  • Correct. This is exactly what elif is shorthand for: an else block whose only content is another if/else.
  • Not valid Python at all — Python has no else if keyword pair (unlike some other languages); this would be a SyntaxError.

Question 2

If an if statement is nested directly inside the body of another if statement, how many spaces of indentation will the body of the inner if statement have?

Show worked solution

The outer if's header sits at 0 spaces, so its body (including the inner if's header) is indented 4 spaces. The inner if is itself a block, so its body is indented another 4 spaces beyond that: 8 spaces.

Question 3

True or false: You can nest if statements inside of other if statements, but not inside of functions.

Select one answer, then check.

  • Not quite. The reading's "If and Functions" section shows exactly this: an if statement nested inside a function's body.
  • Correct. if statements can be nested inside functions just as easily as inside other if statements — adjust_price in the reading does exactly this.

Question 4

True or false: Every if statement must be followed by either an else or an elif.

Select one answer, then check.

  • Not quite. Plenty of examples in this chapter are a bare if with no else/elif at all, such as if age > 21: pass.
  • Correct. else and elif are both optional; an if statement is complete on its own.

Question 5

True or false: The elif is equivalent to an else with an if statement nested inside it.

Select one answer, then check.

  • Correct. The reading states this directly, and Question 1 shows a worked example of the two forms side by side.
  • Not quite. elif offers no new power over an else containing a nested if — it's purely a more convenient way to write the same thing.