Control Flow: Loops Flashcards
6 cards from real Python practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 6 Control Flow: Loops flashcards as text
What is the final value of `total` after this `while` loop finishes?
Answer: 10
The loop executes for `count` values of 0, 1, 2, 3, and 4. The `total` accumulates the sum of these numbers: 0 + 1 + 2 + 3 + 4 = 10. When `count` becomes 5, the condition `5 < 5` is false, and the loop terminates.
In Python, under which circumstance is the `else` block of a `for` loop executed?
Answer: It is only executed if the loop completes all its iterations without being terminated by a `break` statement.
The `else` clause for a loop runs only when the loop has completed its iterations normally. If the loop is exited prematurely with a `break` statement, the `else` block is skipped. It is a way to run code when a `break` was not encountered.
A developer wants to sum only the odd numbers from a list. What will the following code print?
Answer: 9
The `continue` statement skips the remainder of the current iteration and proceeds to the next. When `num` is even (2 and 4), the `continue` statement is executed, and the line `total += num` is skipped. Therefore, only the odd numbers (1, 3, 5) are added to `total`, resulting in 1 + 3 + 5 = 9.
What is the final value of `count` after the following nested loops complete execution?
Answer: 6
This is a nested loop. The outer loop runs 3 times (for i = 0, 1, 2). For each iteration of the outer loop, the inner loop runs completely, which is 2 times (for j = 0, 1). Therefore, the innermost statement `count += 1` is executed a total of 3 * 2 = 6 times.
What will be the output of the following Python code snippet that uses a `break` statement?
Answer: 10
The `for` loop iterates through the numbers generated by `range(10)`. The `break` statement causes the immediate termination of the loop when `i` becomes 5. Consequently, the loop only processes the values of `i` from 0 up to 4. The sum accumulated in `result` is 0 + 1 + 2 + 3 + 4, which equals 10.
Which of the following `while` loops will result in an infinite loop?
Answer: i = 0 while i < 5: i = 1
An infinite loop occurs when the loop's condition never becomes false. In the correct option, `i` is initialized to 0 and the condition `i < 5` is true. Inside the loop, `i` is repeatedly set to 1. Since the value of `i` never changes in a way that would make the condition false (i.e., it never becomes 5 or greater), the loop will run forever.
Written and edited by Nathan Beja, founder of Practice Test Geeks, with AI assistance. We have not yet matched this exam's facts to an official source, so confirm fees, dates and rules with the exam body. Editorial policy