Question Detail

COS 102 If staments Objective Question

Question

In an `if-elif-else` structure, how does Python determine which block of code to execute?
Options
A It executes all `if` and `elif` blocks that are True.
B It randomly picks one block to execute.
C It checks conditions one by one from top to bottom and executes the first block whose condition is True, then skips the rest.
Correct Answer
D It executes the `else` block first, then `elif`, then `if`.
Correct Answer

Option C is the correct answer.

Detailed Explanation

Page 9, 'The "Elif" (Multiple Choices)' slide, notes: 'Python checks these one by one until it finds a True one!'. Once a True condition is found and its block executed, the rest of the elif and else blocks in that structure are skipped.

Hint

Consider the order in which Python evaluates conditions in a multi-choice structure and what happens after a condition is met.

Question Info