Courseiva

CCNA Control Flow Loops Questions

24 of 99 questions · Page 2/2 · Control Flow Loops topic · Answers revealed

76
MCQeasy

A developer writes code to iterate over a list and break when a certain condition is met. Which keyword is used to exit the loop prematurely?

A.break
B.stop
C.exit
D.continue
AnswerA

The break statement immediately terminates the innermost enclosing loop, transferring control to the first statement after it. This matches the stem's requirement to exit prematurely once a condition is met, unlike continue, which skips only the current iteration.

Why this answer

The `break` keyword is used in Python to immediately exit the nearest enclosing loop (for or while) when a specified condition is met, allowing the program to resume execution at the next statement after the loop. This is the standard mechanism for premature loop termination in Python, as defined in the language specification.

Exam trap

Python Institute often tests the distinction between `break` and `continue`, where candidates mistakenly think `continue` can exit a loop, but it only skips the current iteration and proceeds to the next one.

How to eliminate wrong answers

Option B is wrong because `stop` is not a Python keyword; it has no meaning in loop control and would raise a NameError if used. Option C is wrong because `exit` is a function (typically from the `sys` module) used to terminate the entire program, not just the loop, and is not a keyword for loop control. Option D is wrong because `continue` does not exit the loop; it skips the rest of the current iteration and jumps to the next iteration of the loop.

77
Multi-Selecthard

A Python programmer is analyzing a list of integers named numbers. The programmer wants to create a new list that contains only the even numbers from numbers, each multiplied by 10. Which two of the following code snippets correctly produce the desired list? (Choose two.)

Select 2 answers
A.result = [] for n in numbers: if n % 2 == 0: result.append(n * 10)
B.result = [n * 10 for n in numbers if n % 2 != 0]
C.result = [] for n in numbers: if n % 2 == 0: result.append(n) n = n * 10
D.result = [n * 10 for n in numbers if n % 2 == 0]
E.result = [n for n in numbers if n % 2 == 0] * 10
AnswersA, D

This snippet initializes an empty list, iterates over each number, checks if it is even using the modulo operator, and if so appends the number multiplied by 10 to the result list. It correctly filters and transforms the data as required.

Why this answer

The desired output requires filtering even numbers and then multiplying each by 10. The explicit for-loop with append and the list comprehension both correctly perform this filter-and-transform operation. The other options either select odd numbers, fail to multiply, or multiply the list itself instead of its elements.

Exam trap

The trap here is misreading the condition or misunderstanding list multiplication versus element-wise multiplication.

78
MCQmedium

A student grades system: score = 85 if score >= 90: grade = 'A' elif score >= 80: grade = 'B' elif score >= 70: grade = 'C' else: grade = 'F' What grade is assigned?

A.C
B.A
C.B
D.F
AnswerC

With score 85, the first condition (>= 90) fails, so the elif chain evaluates sequentially. The second condition, score >= 80, is true, assigning grade = 'B'. Python stops at the first matching branch, so the remaining elif and else blocks are skipped entirely.

Why this answer

The code uses a cascading if-elif-else structure. Since score is 85, the first condition (score >= 90) is False, so it moves to the elif score >= 80 condition, which is True, assigning grade = 'B'. The remaining elif and else are skipped, making 'B' the correct grade.

Exam trap

The trap here is that candidates might mistakenly think the last matching condition (score >= 70) applies, ignoring that the elif chain stops at the first True condition, leading them to pick 'C' instead of 'B'.

How to eliminate wrong answers

Option A is wrong because 'C' would only be assigned if score >= 70 and score < 80, but 85 is not less than 80. Option B is wrong because 'A' requires score >= 90, and 85 does not meet that condition. Option D is wrong because 'F' is only assigned when all prior conditions are False, which would require score < 70, but 85 is greater than 70.

79
MCQmedium

A Python developer is building a quiz application. The program stores correct answers in a list named `key` and user responses in a list named `answers`. The developer wants to count how many positions match between the two lists, stopping the comparison as soon as the first mismatch is found so that a diagnostic message can be shown. Which control-flow statement should be used inside the loop to stop iterating immediately when a mismatch occurs?

A.return
B.continue
C.pass
D.break
AnswerD

`break` immediately terminates the innermost enclosing loop and transfers control to the first statement after the loop. When a mismatch is found, executing `break` stops further comparisons, allowing the program to exit the loop and present the diagnostic message without processing the remaining positions, which is exactly the stated behavior.

Why this answer

The `break` statement exits the nearest enclosing loop immediately, which is precisely what is needed to stop comparing list positions once the first mismatch appears. `continue` only skips one iteration, `pass` does nothing, and `return` leaves the whole function, so none of those produce the desired early loop termination while preserving subsequent code execution.

Exam trap

The trap here is confusing `continue` with `break`; `continue` skips only the current iteration and lets the loop proceed, so it cannot stop the comparison at the first mismatch as required.

80
Multi-Selectmedium

A Python developer is validating a list of sensor readings stored in `readings`. The developer needs to build a new list containing only readings that are strictly greater than 10. Which two code fragments correctly produce a list of only the values greater than 10? (Choose two.)

Select 2 answers
A.filtered = [r for r in readings if r > 10 else r]
B.filtered = [r for r in readings if r > 10]
C.filtered = list(filter(lambda r: r > 10, readings))
D.filtered = [r for r in readings if r >= 10]
E.filtered = readings.filter(r > 10)
AnswersB, C

This list comprehension iterates over every element in `readings`, evaluates the condition `r > 10`, and includes only those elements for which the condition is true. The result is a new list preserving the original order of qualifying readings, which is exactly the filtered output the developer needs for sensor validation.

Why this answer

A list comprehension with a trailing `if r > 10` and the built-in `filter()` with a lambda both select exactly the elements satisfying the strict comparison, producing the required list. The other fragments either use an inclusive comparison that wrongly keeps 10, call a nonexistent list method, or use invalid comprehension syntax with an `else` clause in the filter position.

Exam trap

The trap here is mixing up strict and inclusive comparison operators and assuming lists expose a `filter()` method, when filtering is done with a comprehension or the built-in `filter()` function.

81
MCQeasy

A developer is writing a Python inventory reconciliation script. They need to examine each element of a list named `stock` and, for every element, execute a block of code that updates a running total. They do not want the loop to terminate early under any condition. Which statement should be placed at the beginning of the loop body to iterate over every element in order?

A.for item in len(stock):
B.for item in stock:
C.for item in range(stock):
D.while item in stock:
AnswerB

This header iterates directly over each element contained in the `stock` list, assigning each value to `item` in order from index 0 to the final index. Because no break or early termination is included, the loop body runs once per element, which matches the requirement to update a running total for every entry without skipping or stopping.

Why this answer

Iterating over a list with `for item in stock:` visits every element in order and assigns each value to the loop variable, making it the direct way to process all entries without early exit. The alternatives misuse `range()`, `len()`, or `while` in ways that either raise errors or fail to traverse the list sequentially, so they cannot accomplish the reconciliation task.

Exam trap

The trap here is assuming that `range()` or `len()` can be used interchangeably with a list in a for loop header, when both actually require an integer and will raise a TypeError if given a list object.

82
MCQeasy

A logistics analyst is writing a Python script that processes a list of shipment weights in kilograms. The analyst needs to display each weight one at a time and also know its position in the list, starting from 1 rather than 0. Which approach most directly accomplishes this?

A.Use for i in range(len(weights)): and print i and weights[i].
B.Use for weight in weights: and print weights.index(weight).
C.Use while weights: and pop the first element each time, printing its value.
D.Use for index, weight in enumerate(weights, start=1): and print index and weight.
AnswerD

The enumerate() function yields pairs of an index and the corresponding element from the iterable. By passing start=1, the counter begins at one instead of the default zero, matching the analyst's requirement to number shipments from 1. This is the idiomatic and most direct way to obtain both position and value in a single loop without manual counter management.

Why this answer

The enumerate() function is designed to pair each element of an iterable with a counter. Supplying start=1 shifts the counter so the first shipment is numbered 1. Other approaches either produce 0-based indexes, mutate the list, or require manual offset adjustments that are easy to get wrong.

Exam trap

The trap here is assuming that list.index() returns the current loop position rather than the first matching element's index.

83
MCQmedium

A company needs to filter a list of temperatures in Celsius to only those above 0, then convert to Fahrenheit (multiply by 9/5 and add 32). Which code snippet correctly accomplishes this using a list comprehension?

A.[t*9/5+32 for t in temps if t>0]
B.[t for t in temps if t>0 then t*9/5+32]
C.[t*9/5+32 for t in temps if t>0 else 0]
D.[t*9/5+32 for t in temps if t>0 else t]
AnswerA

Correct list comprehension with expression and filter.

Why this answer

It uses the standard list comprehension syntax: `[expression for item in iterable if condition]`. Here, `t*9/5+32` is the expression that converts Celsius to Fahrenheit, `for t in temps` iterates over the list, and `if t>0` filters out temperatures at or below zero. This produces a new list containing only the Fahrenheit equivalents of positive Celsius temperatures.

Exam trap

Python Institute often tests the distinction between the filter `if` (placed after the `for` clause) and the conditional expression `if-else` (placed in the expression part), and the trap here is that candidates mistakenly add an `else` to a filter-only comprehension, expecting it to work like a ternary operator.

How to eliminate wrong answers

Option B is wrong because it uses invalid syntax: `if t>0 then t*9/5+32` is not valid in Python list comprehensions; the `if` clause must come after the `for` clause and does not use `then`. Option C is wrong because it includes an `else 0` clause, which is not allowed in a filter-only list comprehension; the `if` at the end is for filtering, not conditional expression, and adding `else` causes a syntax error. Option D is wrong for the same reason: `else t` is invalid syntax when the `if` is used as a filter; a conditional expression (`x if condition else y`) must be placed in the expression part, not after the `if` filter.

84
MCQhard

A log file processing script uses a while loop to read lines until a specific pattern is found. The code currently hangs. The developer suspects an infinite loop. Which change is most likely to fix the issue?

A.Add a break statement after reading the line
B.Increase the sleep time in the loop
C.Replace while with for loop
D.Ensure the condition variable is updated inside the loop
AnswerD

An infinite while loop typically occurs when the controlling condition variable never changes, so the exit condition is never met. Updating that variable inside the loop body ensures the condition eventually becomes false, allowing termination.

Why this answer

An infinite while loop typically occurs when the condition controlling the loop never becomes false. In a log file processing script, the condition variable (e.g., a line counter or a flag indicating the pattern was found) must be updated inside the loop body. Without that update, the loop condition remains true indefinitely, causing the hang.

Adding a `break` statement (option A) would exit the loop unconditionally after the first iteration, which is not the intended fix for a missing update.

Exam trap

Python Institute often tests the misconception that adding a `break` statement is the universal fix for infinite loops, when in fact the root cause is usually a missing update to the loop condition variable, not the absence of an explicit exit command.

How to eliminate wrong answers

Option A is wrong because adding a `break` statement after reading the line would exit the loop immediately after the first iteration, regardless of whether the pattern was found, which is not the intended behavior for processing until a specific pattern is found. Option B is wrong because increasing the sleep time only delays each iteration but does not change the loop condition; the loop would still run forever, just slower. Option C is wrong because replacing `while` with `for` does not inherently fix an infinite loop; if the condition variable is not updated, a `for` loop over a fixed range would terminate, but the problem specifically describes a `while` loop that hangs due to a condition that never becomes false, and a `for` loop would not match the requirement of reading until a pattern is found (it would iterate a fixed number of times).

85
MCQmedium

A student is writing a program that stores the daily steps walked over a week in a list. She wants to determine whether any day had fewer than 1000 steps, and if so, report the first such day's index. Which approach correctly finds the index of the first value below 1000?

A.Use a while loop with a counter that increments only when the step count is below 1000.
B.Use a for loop with range(len(steps)) and break when steps[i] < 1000, then use the loop variable i.
C.Use a for loop over the list elements and break when the element is below 1000, then print the element itself.
D.Use steps.index(min(steps)) to locate the day with the fewest steps.
AnswerB

Iterating with range(len(steps)) gives access to each valid index. When the condition steps[i] < 1000 becomes true, break exits immediately, and the loop variable i still holds the index of that first qualifying day. This is the standard manual-search pattern and correctly reports the earliest index without scanning further elements.

Why this answer

Finding the first element that satisfies a condition requires both the element and its position. Iterating over indices with range(len(steps)) provides the index, and breaking on the first match leaves the loop variable holding that index. Searching for the minimum, iterating over values, or counting qualifying days all answer different questions and cannot report the earliest qualifying index.

Exam trap

The trap here is using a search that finds the smallest value or counts matches, when the requirement is specifically the first position that crosses a threshold.

86
MCQhard

A developer is debugging a script that uses a `while` loop to process items from a queue. The loop is intended to run until the queue is empty, but the script hangs indefinitely. Which of the following is the most likely cause?

A.The `break` statement is missing from the loop body.
B.The loop uses `continue` instead of `break`.
C.The loop condition never becomes false because the queue is not being modified inside the loop.
D.The queue is a list, and lists cannot be used in `while` conditions.
AnswerC

If the queue is not modified within the loop (e.g., items are not removed), the condition `while queue:` remains true forever, causing an infinite loop. The loop must include an operation that eventually makes the condition false, such as `queue.pop()` or `queue.popleft()`, to terminate.

Why this answer

An infinite `while` loop occurs when the loop condition never evaluates to false. If the queue is not being emptied, the condition `while queue:` remains true. The loop body must include an operation that removes items from the queue, such as `pop()` or `popleft()`, to eventually make the condition false and terminate the loop.

Exam trap

The trap here is assuming that a `break` statement is necessary to exit a `while` loop, when actually the loop condition must become false.

87
MCQmedium

A program uses a while loop to find the largest number in a list until a negative number is encountered. What is wrong with this code? numbers = [3, 7, 2, -1, 5] max_num = 0 i = 0 while numbers[i] >= 0: if numbers[i] > max_num: max_num = numbers[i] i += 1 print(max_num)

A.The loop should start with max_num = None.
B.The loop should check all numbers until end of list.
C.The loop should continue even when number is negative (skip negatives).
D.The loop should use a for loop instead.
AnswerC

This is correct. The loop condition should not filter out negatives; instead, it should iterate through the entire list using an index check (e.g., i < len(numbers)), and inside the loop, skip negative numbers with an if statement. This ensures all numbers are considered for finding the largest non-negative number.

Why this answer

The while loop condition `numbers[i] >= 0` causes the loop to terminate as soon as it encounters a negative number (-1), so it never processes the number 5 at the end of the list. The intended behavior is to skip negative numbers and continue iterating through the entire list to find the largest number among all non-negative values. To fix this, the loop should use a condition that checks the index against the list length (e.g., `i < len(numbers)`) and then skip negative numbers with an `if` statement inside the loop.

Exam trap

Python Institute often tests the misconception that a while loop's condition should mirror the data filter (e.g., 'continue while number is non-negative'), when in reality the condition should control the iteration range (e.g., index within bounds) and the filter should be an inner `if` statement.

How to eliminate wrong answers

Option A is wrong because initializing `max_num` to `None` would cause a `TypeError` when comparing with an integer using `>` (e.g., `None > 3` is not valid in Python 3). Option B is wrong because the loop does not check all numbers until the end of the list; it stops early due to the negative number condition, but the core issue is the loop's termination condition, not the lack of a full traversal. Option D is wrong because a `for` loop would not inherently fix the problem; the same flawed logic (stopping at a negative number) could be replicated with a `for` loop if a `break` is used, and the question asks specifically about the while loop's logic error.

88
Multi-Selectmedium

A developer is reviewing loop constructs that iterate over the list scores = [10, 20, 30]. Which two statements about iterating this list are true? (Choose two.)

Select 2 answers
A.for s in scores: assigns s to each index position, so s holds 0, 1, and 2 during iteration.
B.for s in scores: accesses each element value directly, so s takes the values 10, 20, and 30 in order.
C.for i in range(len(scores)): gives i the values 0, 1, and 2, which can be used to index scores.
D.Modifying scores by appending a new element during a for loop over scores reliably processes the appended element in the same loop.
E.A for loop over scores always executes at least once, even when the list is empty.
AnswersB, C

Iterating a list directly yields its elements, so the loop variable receives 10, then 20, then 30. This is the most direct way to read values when the positions are not needed. The list itself is not modified, and the order follows the list's internal sequence, which here matches the order in which the values were written.

Why this answer

Python lets you iterate a list either by value, where the loop variable receives each element, or by index, where a range over the list's length supplies positions usable with subscripting. Direct value iteration is simplest for reading data, while index iteration is needed when positions matter. Appending during iteration is unreliable, and an empty list produces no iterations.

Exam trap

The trap here is assuming a plain for loop over a list provides indices, when it actually yields element values.

89
MCQhard

A data analyst is processing a large dataset of customer transactions. The dataset is stored as a list of dictionaries, each with keys 'amount' and 'date'. The analyst needs to compute the total revenue for 2024. They write: total = 0 for t in transactions: if t['date'].year == 2024: total += t['amount'] They then run it and get a KeyError: 'date'. After inspection, they notice that some records have a 'Date' key (capital D) instead. The analyst wants to fix this without modifying the data. Which approach will correctly sum amounts regardless of key case?

A.Change the if condition to: if t.get('date', t.get('Date')).year == 2024
B.Use a try-except block to catch KeyError and use alternative key
C.Convert all keys to lowercase before processing
D.Use a list comprehension with conditional chaining
AnswerA

Correct: get with fallback handles both key casings.

Why this answer

`dict.get(key, default)` safely attempts to retrieve the value for 'date', and if that key is missing, it falls back to retrieving the value for 'Date'. This handles the case inconsistency without modifying the original data and avoids a KeyError. The `.year` attribute is then accessed on the returned date object.

Exam trap

Python Institute often tests the distinction between direct key access (`dict[key]`) which raises KeyError, and the safer `dict.get()` method, and the trap here is that candidates may think a try-except block is the only way to handle missing keys, overlooking the more Pythonic and concise `.get()` with a fallback.

How to eliminate wrong answers

Option B is wrong because a try-except block would work but is less Pythonic and less efficient than using `.get()` with a fallback; it also requires an extra nested block and is not the simplest fix. Option C is wrong because converting all keys to lowercase would require modifying the data (e.g., creating new dictionaries), which violates the requirement 'without modifying the data'. Option D is wrong because a list comprehension with conditional chaining does not directly solve the key-case issue; it would still need a way to handle the missing key, and chaining conditions like `if t.get('date', t.get('Date')).year == 2024` is essentially the same as option A but in a comprehension, not a fundamentally different approach.

90
MCQmedium

A ticket system stores seat rows in the list rows = [[1, 2], [3, 4], [5, 6]]. A developer needs to print every individual seat number on its own line, in order, from 1 through 6. Which code accomplishes this?

A.print(rows)
B.for row in rows: print(row)
C.for seat in rows: print(seat[0])
D.for row in rows: for seat in row: print(seat)
AnswerD

The outer loop selects each inner list, and the inner loop walks that list element by element, printing 1, 2, 3, 4, 5, and 6 each on its own line. Nested loops are the standard way to traverse a list of lists, and the order is preserved because both loops advance forward through their sequences.

Why this answer

Traversing a list of lists requires nested loops: the outer loop yields each inner list, and the inner loop yields each element within it. Printing the inner element inside both loops emits every seat number in order, one per line, which matches the required output of 1 through 6.

Exam trap

The trap here is stopping at one level of iteration and printing whole inner lists instead of their individual elements.

91
MCQhard

A Python developer is writing a script that processes a list of temperatures in a loop. Inside the loop, a conditional block handles sub-zero readings by appending a warning to a report. The developer notices that the loop body is executing even for temperatures that are not sub-zero. Which statement about Python's `if`/`elif`/`else` structure explains why a block guarded by `if temp < 0:` should not execute for a temperature of 5?

A.The `if` block executes whenever the loop variable is reassigned, regardless of the condition's truth value.
B.The `if` block executes only if a previous `elif` condition was also False, making it dependent on sibling clauses.
C.The `if` block executes for every iteration because Python evaluates conditions after running the block once.
D.The `if` block executes only when its condition evaluates to a truthy value; since `5 < 0` is False, the block is skipped.
AnswerD

Python evaluates the condition `temp < 0` and, for a temperature of 5, produces the boolean False. A false condition causes the indented block under `if` to be skipped entirely, and control passes to any `elif` or `else` clause or to the next statement after the structure. This is the fundamental rule governing conditional execution.

Why this answer

Conditional blocks in Python execute based on the truth value of their condition, evaluated before the block runs. Because `5 < 0` is False, the guarded block is skipped and control moves on. The other statements misdescribe evaluation order, trigger conditions, or dependencies among sibling clauses, none of which match Python's top-down conditional evaluation model.

Exam trap

The trap here is assuming an `if` block can be triggered by side effects like variable reassignment or sibling clauses, when only the truth value of its own condition controls execution.

92
MCQmedium

A system administrator is writing a Python script to monitor server uptime. The script reads a log file line by line, parses timestamps, and stores them in a list. It then loops through the list to detect gaps longer than 5 minutes that indicate a crash. However, the script keeps missing crashes. The current loop is a for loop that iterates over the list using indices. The administrator suspects the loop logic. The loop uses 'for i in range(len(timestamps)-1): if timestamps[i+1] - timestamps[i] > 300: print("Crash detected")'. Timestamps are integers representing seconds since epoch. What is the most likely cause of missed crashes and the best fix?

A.The loop should use range(len(timestamps)) instead of -1
B.The difference should be computed as timestamps[i] - timestamps[i+1]
C.The comparison should be > 300, but use > 300.0
D.The timestamps list may not be sorted
AnswerD

Unsorted timestamps break the adjacent-pair comparison: the loop only checks consecutive list entries, so a genuine gap can sit between values that are not neighbours in time. Sorting the list before looping restores chronological adjacency, ensuring every real interval exceeding 300 seconds is detected.

Why this answer

The loop assumes timestamps are in chronological order, but if the list is unsorted, adjacent elements may not represent consecutive events, causing the time difference to be negative or misleading, and thus missing actual gaps. Sorting the list before the loop ensures that timestamps[i+1] - timestamps[i] correctly reflects the time between consecutive log entries.

Exam trap

Python Institute often tests the assumption that data structures are in the expected order, and the trap here is that candidates focus on off-by-one errors or type issues while overlooking the fundamental requirement that the list must be sorted for pairwise difference logic to work.

How to eliminate wrong answers

Option A is wrong because using range(len(timestamps)) would cause an IndexError on the last iteration when accessing timestamps[i+1]. Option B is wrong because subtracting timestamps[i] from timestamps[i+1] (assuming sorted order) gives a positive difference for increasing timestamps, which is correct; reversing the order would yield negative values that never exceed 300. Option C is wrong because comparing integers with > 300 is functionally identical to > 300.0 in Python; the type mismatch does not affect comparison logic.

93
MCQeasy

An inventory script stores product quantities in a list named stock. The script must print the running total of quantities from the start of the list up to, but not including, the first zero quantity it encounters. Which code fragment produces this behavior?

A.total = 0 for q in stock: total += q if q == 0: break print(total)
B.total = 0 for q in stock: if q == 0: break total += q print(total)
C.total = 0 for q in stock: if q == 0: continue total += q print(total)
D.total = 0 for q in stock: total += q if q == 0: continue print(total)
AnswerB

This loop adds each quantity to total and immediately exits with break when a zero is found, so only elements before the first zero are summed. Because the test occurs before the addition, the zero itself is never added, matching the requirement exactly.

Why this answer

The requirement is to accumulate quantities until the first zero appears, then stop without adding that zero. Placing the zero test before the addition and exiting with break achieves exactly this, because the loop terminates before the zero can be added to the running total.

Exam trap

The trap here is assuming that break and continue behave the same way inside a loop when they actually exit versus skip.

94
MCQmedium

A developer needs to implement a loop that prints numbers from 10 down to 1. Which loop correctly achieves this?

A.for i in range(10, 0, -1): print(i)
B.for i in range(10, 0): print(i)
C.for i in reversed(range(1, 10)): print(i)
D.for i in range(10, 1, -1): print(i)
AnswerA

range(10, 0, -1) starts at 10, stops before 0, and steps by -1, yielding 10 down to 1. The stop value is exclusive, so 0 is correctly omitted, matching the descending sequence the developer requires.

Why this answer

`range(10, 0, -1)` generates numbers from 10 down to 1 inclusive. The start is 10, the stop is 0 (exclusive), and the step is -1, so the sequence is 10, 9, 8, ..., 1. This matches the requirement exactly.

Exam trap

Python Institute often tests the exclusive nature of the stop argument in `range()`, leading candidates to forget that the stop value is never included in the sequence.

How to eliminate wrong answers

Option B is wrong because `range(10, 0)` defaults to a step of 1, and since start > stop with a positive step, it produces an empty sequence — nothing is printed. Option C is wrong because `reversed(range(1, 10))` yields numbers from 9 down to 1, missing 10 entirely. Option D is wrong because `range(10, 1, -1)` stops at 2 (since stop is exclusive), so it prints 10 down to 2, missing 1.

95
MCQeasy

Which loop is more efficient for iterating over a large list when you only need the values, not indices?

A.for i in range(len(mylist)): value = mylist[i]
B.for i, value in enumerate(mylist):
C.for value in mylist:
D.for value in mylist[::-1]:
AnswerC

Iterating directly with `for value in mylist` avoids index lookups and the overhead of `range()` and `len()` calls, yielding each element straight from the list's iterator. This satisfies the stem's efficiency constraint for large lists where indices are unnecessary, giving cleaner, faster traversal than index-based loops.

Why this answer

Iterating directly over the list with `for value in mylist:` avoids the overhead of indexing or enumeration. This is the most efficient approach in Python for accessing only the values, as it uses the list's internal iterator, which is implemented in C and involves no function calls or index lookups per iteration.

Exam trap

Python Institute often tests the misconception that `enumerate()` is always the best choice for iteration, but the trap here is that candidates overlook the specific requirement ('only the values, not indices') and choose a more general but less efficient option like B or A.

How to eliminate wrong answers

Option A is wrong because it uses `range(len(mylist))` and then accesses each element via indexing (`mylist[i]`), which adds the overhead of calling `range()` and performing a list lookup each iteration, making it less efficient. Option B is wrong because `enumerate()` yields both index and value, which is unnecessary when only values are needed, adding the overhead of tuple unpacking and an extra counter. Option D is wrong because `mylist[::-1]` creates a reversed copy of the entire list in memory, which is both time- and space-inefficient for large lists, and then iterates over that copy.

96
Multi-Selecthard

A developer is writing a Python script to process a list of integers representing inventory counts. The developer needs to iterate over the list and, for each element, perform an action, but also needs to be able to terminate the entire loop early when a sentinel value (0) is encountered. Which two statements about loop control in Python are correct? (Choose two.)

Select 2 answers
A.The continue statement terminates the loop and resumes execution after the loop.
B.The continue statement skips the rest of the current iteration and proceeds to the next iteration of the loop.
C.The break statement immediately exits the innermost enclosing loop.
D.A for loop in Python automatically stops when it encounters a None value in the sequence.
E.The break statement can be used outside a loop to exit a function early.
AnswersB, C

The continue statement abandons the remaining statements in the current loop body and jumps to the next iteration. It does not terminate the loop. In the inventory scenario, continue could be used to skip processing for a particular value while still examining subsequent elements, which is different from early termination.

Why this answer

The break statement exits the innermost loop immediately, which is suitable for stopping on a sentinel value. The continue statement skips to the next iteration without terminating the loop. These two control statements are fundamental for managing loop execution and are distinct from return, which exits a function.

Exam trap

The trap here is confusing break with return or assuming that continue terminates the loop, when it only skips the current iteration.

97
Drag & Dropmedium

Arrange the steps to handle an exception in Python using try-except.

Drag or tap steps into the slots.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

Exception handling wraps risky code in try, catches exceptions with except, and optionally includes else and finally.

98
MCQmedium

A quality engineer tracks defect counts per shift in a list called defects. She needs the running total of all defects after every shift, producing a list of cumulative sums with the same length as defects. Which approach produces that cumulative list?

A.cumulative = [] for d in defects: cumulative.append(sum(defects))
B.total = 0 cumulative = [] for d in defects: cumulative.append(total) total += d
C.cumulative = [defects[i] + defects[i+1] for i in range(len(defects))]
D.total = 0 cumulative = [] for d in defects: total += d cumulative.append(total)
AnswerD

The accumulator total starts at zero, and each iteration adds the current defect count before appending the updated total to the new list. Because the append happens after the addition, the resulting list holds the cumulative sum at each shift and has exactly the same length as the defects list, which is what the engineer needs.

Why this answer

A running total requires an accumulator initialized before the loop, updated with each element, and recorded after the update. Appending after adding yields a cumulative value for every shift and keeps the output length equal to the input length. Appending before adding shifts all values by one position, and recomputing the whole-list sum each iteration produces a repeated grand total instead.

Exam trap

The trap here is placing the append before the addition, which yields a list that is shifted by one and never reaches the final total.

99
Multi-Selecthard

Which three of the following statements about lists are true? (Choose three.)

Select 3 answers
A.Lists can be indexed with integers.
B.Lists can be sliced to create a new list.
C.Lists are mutable.
D.Lists have a fixed size once created.
E.Lists can only contain elements of the same data type.
AnswersA, B, C

Indexing starts at 0.

Why this answer

Lists in Python are ordered sequences that support indexing with integers, starting from 0 for the first element and negative integers for reverse indexing. This allows direct access to any element by its position, a fundamental feature of sequence types in Python.

Exam trap

Python Institute often tests the misconception that lists are fixed-size or homogeneous, similar to arrays in other languages, to catch candidates who confuse Python lists with static arrays or typed collections.

← PreviousPage 2 of 2 · 99 questions total

Ready to test yourself?

Try a timed practice session using only Control Flow Loops questions.