Courseiva

CCNA Control Flow, Loops, Lists and Logic Questions

75 of 99 questions · Page 1/2 · Control Flow, Loops, Lists and Logic · Answers revealed

1
MCQeasy

What does the following code print? x = 10 if x > 5: if x > 15: print("A") else: print("B") else: print("C")

A.No output
B.C
C.B
D.A
AnswerC

x equals 10, so the outer condition x > 5 is true and the inner block runs. The inner test x > 15 is false, so the else branch executes, printing B. The outer else is skipped entirely.

Why this answer

The code first checks if x > 5, which is true because x = 10. Then it checks if x > 15, which is false, so the else branch of the inner if-else executes, printing 'B'. The outer else is skipped entirely.

Exam trap

Python Institute often tests the misconception that the outer else (printing 'C') will execute when the inner condition fails, but candidates must remember that the outer else only runs if the outer condition is false.

How to eliminate wrong answers

Option A is wrong because the code does produce output; the inner else branch executes. Option B is wrong because 'C' would only print if the outer condition x > 5 were false, but it is true. Option D is wrong because 'A' would print only if x > 15 were true, but x = 10 is not greater than 15.

2
Multi-Selecteasy

Which two of the following are valid ways to create a list with elements 1, 2, 3? (Select two.)

Select 2 answers
A.list = list(range(1, 4))
B.list = [1, 2, 3]
C.list = [1, 2, 3]]
D.list = (1, 2, 3)
E.list = [1; 2; 3]
AnswersA, B

Valid: range creates sequence, list() converts to list.

Why this answer

`list(range(1, 4))` creates a list from the range object that generates numbers 1, 2, and 3 (the `range` function stops before the stop value 4). This is a common Python idiom for converting a range into a list.

Exam trap

Python Institute often tests the distinction between list literals (square brackets) and tuple literals (parentheses), and the requirement for commas as separators, to catch candidates who confuse syntax from other languages or misuse punctuation.

3
MCQmedium

A logistics coordinator stores shipment weights in a list `weights = [12, 18, 7, 25]`. She needs to find the average weight of all shipments. Which code snippet correctly computes and prints the average?

A.print(total(weights) / len(weights))
B.print(mean(weights) / len(weights))
C.print(sum(weights) // len(weights))
D.print(sum(weights) / len(weights))
AnswerD

This uses the built-in `sum()` to total all elements and divides by the count from `len()`, yielding the arithmetic mean. For the given list, the sum is 62 and the length is 4, so the average is 15.5. This is the standard, concise Python approach for averaging a list of numbers.

Why this answer

The average is calculated by dividing the sum of all elements by the number of elements. The built-in `sum()` and `len()` functions provide these values directly, and the `/` operator returns a float result. The other options either use incorrect functions or perform integer division, which loses the fractional part.

Exam trap

The trap here is confusing the floor division operator `//` with true division `/`, leading to a truncated result instead of the exact average.

4
MCQhard

A program contains a nested while loop. The inner loop should run as long as a condition is True, but the outer loop should stop after 3 iterations. Which code structure is correct? (Assume the inner loop condition is inner < 5.)

A.for outer in range(3): inner = 0 while inner < 5: # do something inner += 1
B.outer = 0 while outer < 3: for inner in range(5): # do something outer += 1
C.outer = 0 while outer < 3: inner = 0 while inner < 5: # do something outer += 1 inner += 1
D.outer = 0 while outer < 3: inner = 0 while inner < 5: # do something inner += 1 outer += 1
AnswerD

Correct; outer increments after inner loop completes.

Why this answer

Ly implements a nested while loop where the inner loop runs while `inner < 5` and the outer loop runs while `outer < 3`. The inner loop increments `inner` to control its own termination, and the outer loop increments `outer` after the inner loop completes, ensuring exactly 3 iterations of the outer loop. This matches the requirement that the outer loop stops after 3 iterations while the inner loop runs as long as its condition is True.

Exam trap

Python Institute often tests the misconception that incrementing a loop counter inside a nested loop will correctly control both loops, when in fact it causes the outer loop to terminate prematurely, as seen in options B and C.

How to eliminate wrong answers

Option A is wrong because it uses a `for` loop for the outer loop, not a `while` loop as specified in the question (the outer loop should be a `while` loop, not a `for` loop). Option B is wrong because it increments `outer` inside the inner `for` loop, causing the outer `while` loop to terminate prematurely after the first inner iteration (since `outer` becomes 3 after one pass through the inner loop). Option C is wrong because it increments `outer` inside the inner `while` loop, which also causes the outer loop to terminate early (after the first inner iteration) and disrupts the intended 3 outer iterations.

5
MCQeasy

A list of numbers is defined as nums = [1, 2, 3, 4, 5]. Which expression returns the last element?

A.nums[5]
B.nums[-1]
C.nums[0]
D.nums[-2]
AnswerB

Negative indexing counts from the end of the sequence, so nums[-1] refers to the final element, 5. This satisfies the stem's requirement for retrieving the last element without computing its index from the list length.

Why this answer

Python uses zero-based indexing, so the first element is at index 0 and the last element is at index -1. Negative indices count from the end of the list, so nums[-1] directly accesses the last element (5) without needing to know the list length.

Exam trap

The trap here is that candidates often forget Python's zero-based indexing and mistakenly think the last element is at index equal to the list length (e.g., nums[5]), or they confuse negative indexing and pick nums[-2] thinking it refers to the last element.

How to eliminate wrong answers

Option A is wrong because it attempts to access index 5, which is out of range for a list of length 5 (valid indices are 0 through 4), and will raise an IndexError. Option C is wrong because nums[0] returns the first element (1), not the last. Option D is wrong because nums[-2] returns the second-to-last element (4), not the last.

6
MCQmedium

A logistics coordinator tracks delivery statuses in a list of strings. The coordinator wants to build a new list containing only the statuses that are not equal to `"delivered"`, preserving the original order. Which code fragment produces the desired list `pending`?

A.pending = statuses.remove("delivered")
B.pending = [s for s in statuses if not "delivered"]
C.pending = [s for s in statuses if s != "delivered"]
D.pending = [s for s in statuses if s == "delivered"]
AnswerC

This list comprehension iterates every status, keeps only those whose value differs from `"delivered"`, and collects them in the original order. It is concise and equivalent to an explicit loop with a conditional append. Because the condition is evaluative rather than terminating, all non-delivered entries are retained regardless of position.

Why this answer

Selecting all entries that differ from a target value calls for a comprehension whose condition compares each element with `!=`. That preserves order and includes every non-matching status. Inverting the comparison keeps the wrong subset, `remove` mutates and returns `None`, and testing the literal's truthiness yields nothing at all.

Exam trap

The trap here is writing `not "delivered"` as if it compared a variable, when it actually negates a non-empty string literal.

7
MCQeasy

A developer is writing a Python script that should keep prompting for a password until the user enters the correct one. The script must not run forever if the user never guesses correctly, so it should give up after 5 attempts. Which loop construct is most appropriate for this scenario?

A.A for loop that iterates over the characters of the password string, comparing each character.
B.A for loop that iterates over range(5), checking the password inside and breaking when correct.
C.A while True loop with no break statement, relying on the password check to terminate.
D.A while loop that continues as long as the entered password is incorrect, with no attempt counter.
AnswerB

A for loop over range(5) runs exactly five times, providing a natural attempt limit. Inside, an if statement can compare the input to the stored password and break early when it matches, so the loop stops as soon as the correct value is entered, satisfying both the retry and the give-up-after-five requirement without any manual counter management.

Why this answer

The requirement combines a fixed maximum number of attempts with the possibility of stopping early on success. A for loop over range(5) supplies the exact bound of five iterations, and a break inside ends the loop as soon as the password matches. The other constructs either loop forever when the user keeps failing or do not model repeated input attempts at all.

Exam trap

The trap here is assuming that a while loop checking the password is equivalent to a bounded retry loop, when in fact it can run forever if the password is never correct.

8
MCQeasy

A junior developer writes a Python script to sum all numbers greater than 10 from a list. The code is: numbers = [5, 12, 8, 15, 3] total = 0 for num in numbers: if num > 10: total = total + 1 print(total) The output is 2, but the expected sum is 27 (12+15). Which change will produce the correct output?

A.Change `total = 0` to `total = []`
B.Change `total = total + 1` to `total += num`
C.Change `if num > 10:` to `if num >= 10:`
D.Change `for num in numbers:` to `for num in range(numbers):`
AnswerB

Replacing the increment with `total += num` accumulates each qualifying value rather than counting matches, satisfying the stem's requirement to sum numbers greater than 10. The `if num > 10` filter already isolates 12 and 15, so the accumulator yields 27 instead of the tally 2.

Why this answer

The original code increments `total` by 1 for each qualifying number, counting them instead of summing their values. Changing `total = total + 1` to `total += num` adds the actual number to the accumulator, producing the correct sum of 12 + 15 = 27.

Exam trap

The trap here is that candidates often confuse counting with summing — they see `total = total + 1` and think it's accumulating values, but it actually increments by a constant, not by the variable `num`.

How to eliminate wrong answers

Option A is wrong because changing `total = 0` to `total = []` makes `total` a list, and `total + 1` would cause a TypeError (cannot concatenate list and int). Option C is wrong because changing `if num > 10:` to `if num >= 10:` would include the number 10 (if present), but the list has no 10, so it does not fix the core issue of counting instead of summing. Option D is wrong because `range(numbers)` is invalid — `range()` expects integer arguments, not a list; this would raise a TypeError.

9
MCQhard

Given the code: x = [1, 2, 3] y = x y.append(4) print(x) What is the output?

A.Error
B.[1, 2, 3]
C.[1, 2, 3, 4]
D.[1, 2, 3, 4, 5]
AnswerC

Assignment binds y to the same list object as x, not a copy. Calling append mutates that shared object in place, so the single list now holds four elements and printing x reflects the change.

Why this answer

In Python, variables hold references to objects, not the objects themselves. When `y = x` is executed, both `x` and `y` point to the same list object in memory. The `y.append(4)` method modifies that shared list in-place, so the change is reflected when `x` is printed, outputting `[1, 2, 3, 4]`.

Exam trap

Python Institute often tests the distinction between variable assignment and object copying, trapping candidates who mistakenly think `y = x` creates a separate copy of the list, leading them to choose option B.

How to eliminate wrong answers

Option A is wrong because no error occurs; the code runs successfully and produces a list. Option B is wrong because it assumes `y = x` creates a copy of the list, but Python does not copy objects on assignment; both variables reference the same mutable list. Option D is wrong because only one element (4) is appended, not two; the value 5 is never added.

10
MCQhard

A network engineer writes a script to validate IP addresses. The script checks each octet and prints 'Valid' if all octets are between 0 and 255, otherwise 'Invalid'. However, the script always prints 'Invalid' for valid IPs. The code uses a for loop with an else clause. Which logical error is likely?

A.The list of octets is not properly split
B.The condition uses 'or' instead of 'and'
C.The else clause is indented incorrectly
D.The for loop's else clause executes when the loop completes without break, but the engineer expects else to run when break occurs
AnswerD

Common misunderstanding of for-else; else runs on normal completion.

Why this answer

In Python, a `for` loop's `else` clause executes only when the loop completes normally (i.e., without hitting a `break`). The engineer likely intended the `else` to run when an invalid octet is found (triggering a `break`), but instead the `else` runs when all octets are valid and the loop finishes without breaking, causing the script to always print 'Invalid' when the validation logic is inverted.

Exam trap

Python Institute often tests the `for...else` behavior by reversing the expected logic, trapping candidates who assume `else` runs only on error or break, rather than on normal loop completion.

How to eliminate wrong answers

Option A is wrong because if the list of octets were not properly split, the script would likely raise an error or produce incorrect comparisons, not consistently print 'Invalid' for valid IPs. Option B is wrong because using 'or' instead of 'and' in the condition would cause the check to pass if any octet is within range, leading to false 'Valid' prints, not always 'Invalid'. Option C is wrong because incorrect indentation of the `else` clause would cause a syntax error or change the block association, not a consistent logical error where the `else` always runs.

11
MCQeasy

A developer is writing a simple number guessing game. The computer picks a random number between 1 and 100, and the user keeps guessing until correct. The developer implements: secret = random.randint(1,100) guess = 0 while guess != secret: guess = int(input("Guess: ")) if guess == secret: print("Correct!") else: print("Wrong, try again.") The game works, but the developer notices that if the user enters something that is not an integer, the program crashes. Which modification ensures the program handles non-integer input gracefully?

A.Use a while True loop with break
B.Change the data type of guess to string
C.Use a try-except around the input conversion
D.Add an if statement to check if input is digit
AnswerC

Wrapping the int(input(...)) conversion in try-except catches ValueError when non-numeric text is entered, letting the loop prompt again instead of crashing. This directly addresses the stem's constraint that non-integer input must be handled gracefully without terminating the guessing game.

Why this answer

Wrapping the `int(input(...))` in a `try-except` block catches the `ValueError` that occurs when the user enters a non-integer string. This allows the program to handle the error gracefully (e.g., by printing a message and continuing the loop) instead of crashing. The other options do not prevent the crash when `int()` receives invalid input.

Exam trap

Python Institute often tests the distinction between input validation (like `isdigit()`) and exception handling (`try-except`), where candidates mistakenly believe checking for digits is sufficient, ignoring that `int()` can still fail on valid-looking strings like '-5' or ' 10'.

How to eliminate wrong answers

Option A is wrong because using a `while True` loop with `break` does not handle the `ValueError` from `int()`; it only changes the loop structure, not the input conversion safety. Option B is wrong because changing `guess` to a string would prevent integer comparison with `secret`, breaking the game logic entirely. Option D is wrong because checking if the input is a digit (e.g., `input().isdigit()`) only works for positive integers and fails for negative numbers, floats, or other valid integer representations like `-5` or `+3`, and still requires a conversion that could raise an error.

12
MCQmedium

A data analyst has a list named readings containing numeric sensor values. She needs to build a new list that contains only the values strictly greater than 10, preserving their original order. Which code fragment produces this result?

A.filtered = [x for x in readings if x >= 10]
B.filtered = [x for x in readings if x > 10]
C.filtered = [x > 10 for x in readings]
D.filtered = [x for x in readings if x > 10][::-1]
AnswerB

This list comprehension iterates over readings in order, keeps each element only when x > 10, and collects the survivors into a new list. Because iteration follows the original sequence, the relative order of the kept values is preserved. It also leaves the original readings list unchanged, which matches the analyst's need to derive a filtered list rather than modify the source data.

Why this answer

A filtering list comprehension keeps only the elements that satisfy the condition and preserves their original order. Writing the element expression as x and placing the comparison after if yields the desired numeric values. Using an inclusive comparison admits boundary values, putting the comparison itself in the expression yields Booleans, and appending a reverse slice destroys the original ordering.

Exam trap

The trap here is confusing the expression position with the condition position in a comprehension, which turns a filter into a list of Boolean results.

13
Multi-Selecteasy

Which two of the following list methods modify the original list in place? (Choose two.)

Select 2 answers
A.sort()
B.count()
C.sorted()
D.append()
E.copy()
AnswersA, D

sort() reorders the list object itself, mutating the existing sequence rather than returning a new list. This in-place behaviour is the axis distinguishing it from non-mutating methods such as sorted(), which builds a separate list and leaves the original untouched.

Why this answer

Option A, sort(), is correct because it is a list method that reorders the list's elements directly in the existing list object and returns None, so the original list is modified in place. Option D, append(), is correct because it adds a single element to the end of the existing list object and also returns None, mutating the original list. Option B, count(), is not correct because it only returns the number of occurrences of a value and does not change the list.

Option C, sorted(), is not correct because it is a built-in function that returns a new sorted list, leaving the original list unchanged. Option E, copy(), is not correct because it returns a shallow copy of the list without modifying the original list.

Exam trap

Python Institute often tests the distinction between methods that mutate the list in place (like `sort()`) and functions that return a new list (like `sorted()`), as well as the fact that `count()` and `copy()` are non-mutating, to see if candidates confuse method behavior with function behavior.

14
MCQmedium

A Python developer is writing a script that processes a list of sensor readings stored in the variable readings. The developer needs to iterate over the list and print each reading, but wants the loop to stop immediately if a reading of -999 is encountered, because that value indicates a sensor malfunction. Which code snippet correctly implements this behavior?

A.for reading in readings: if reading == -999: break print(reading)
B.for reading in readings: if reading != -999: print(reading) else: break
C.for reading in readings: print(reading) if reading == -999: break
D.for reading in readings: if reading == -999: continue print(reading)
AnswerA

This snippet iterates over each element in readings, checks if the current reading equals -999, and if so executes break to exit the loop immediately. The print statement is placed after the if block, so it only executes for non-malfunction readings. This matches the requirement exactly.

Why this answer

The correct implementation must iterate over the list, check for the malfunction value, and break immediately without printing that value. The snippet that places the break inside the if block and the print after the if block ensures that normal readings are printed and the loop terminates upon encountering -999. This matches the specified behavior precisely.

Exam trap

The trap here is confusing break with continue, where continue skips only the current iteration but does not stop the loop.

15
MCQeasy

A student is writing a Python script to sum all even numbers in a list `nums`. The script should ignore odd numbers. Which code correctly computes the sum?

A.total = sum(nums) if nums % 2 == 0 else 0
B.total = 0 for n in nums: if n / 2 == 0: total += n
C.total = 0 for n in nums: if n % 2 == 1: total += n
D.total = 0 for n in nums: if n % 2 == 0: total += n
AnswerD

This loop checks each number for evenness using the modulo operator; if the remainder when divided by 2 is zero, the number is added to the total. Odd numbers are skipped. This correctly sums only the even numbers in the list, matching the student's requirement.

Why this answer

The correct loop uses the modulo operator to test whether each number is even, and adds only those numbers to the running total. This directly implements the requirement to sum even numbers while ignoring odd ones, using a standard accumulator pattern in Python.

Exam trap

The trap here is confusing the modulo condition for even numbers with the one for odd numbers, or mistakenly using division instead of modulo.

16
MCQmedium

A developer needs to iterate over a list of network interfaces and print only the names that start with 'eth'. Which code should be used?

A.for i in range(len(interfaces)): if 'eth' in interfaces[i]: print(interfaces[i])
B.for iface in interfaces: if iface[:3] is 'eth': print(iface)
C.for iface in interfaces: if iface.startswith('eth'): print(iface)
D.for iface in interfaces: if 'eth' in iface: print(iface)
AnswerC

Iterating directly over `interfaces` yields each element, and `str.startswith('eth')` performs the required prefix test, printing only matching names. This satisfies the stem's constraint of filtering by the 'eth' prefix without indexing or slicing, keeping the loop concise and readable.

Why this answer

The `startswith()` string method is the most direct and readable way to check if each interface name begins with the substring 'eth'. This approach avoids unnecessary slicing or substring membership checks, making the intent clear and the code efficient.

Exam trap

Python Institute often tests the distinction between `in` (substring membership) and `startswith()` (prefix matching), leading candidates to choose Option D because they think 'eth' must appear at the start, but `in` would also match names like 'xeth0'.

How to eliminate wrong answers

Option A is wrong because it uses `range(len(interfaces))` and index-based access, which is unnecessarily complex and less Pythonic; also `'eth' in interfaces[i]` checks if 'eth' appears anywhere in the string, not just at the start. Option B is wrong because it uses the `is` operator to compare strings, which checks identity (memory address) rather than equality; `is` should never be used for string value comparison. Option D is wrong because `'eth' in iface` returns True if 'eth' appears anywhere in the interface name (e.g., 'xeth0' or 'eth0backup'), not only at the beginning.

17
MCQhard

Refer to the exhibit. What does the else clause of the inner for loop do?

A.Executes if the outer loop condition is false.
B.Executes if the inner loop is broken, meaning an even number was found.
C.Executes if the inner loop completes without break, meaning no even number in the row.
D.Executes after each iteration of the inner loop.
AnswerC

The else clause attached to a for loop runs only when the loop exhausts its iterable without hitting a break, so it executes when no even number appears in the row. A break would skip it entirely.

Why this answer

The else clause of a for loop in Python executes only when the loop completes normally, i.e., without encountering a break statement. In this nested loop, the inner for iterates over elements of a row; if no even number is found (no break), the else triggers, indicating the row has no even numbers. This is why option C is correct.

Exam trap

The PCEP exam often tests the for-else behavior by making candidates confuse it with the if-else pattern, leading them to think the else runs after every iteration or when a condition is false, rather than understanding it as a 'no-break' indicator.

How to eliminate wrong answers

Option A is wrong because the else clause belongs to the inner for loop, not the outer loop, and it has no connection to the outer loop's condition. Option B is wrong because the else clause executes precisely when the loop is NOT broken; if an even number is found and break executes, the else is skipped. Option D is wrong because the else clause executes only once after the entire inner loop finishes (if no break), not after each iteration.

18
Multi-Selecthard

A programmer is writing a Python function that processes a list of integers. The function must remove all negative numbers from the list while preserving the order of the remaining elements, and it must do so in place (modifying the original list). Which two code snippets correctly achieve this? (Choose two.)

Select 2 answers
A.i = 0 while i < len(numbers): if numbers[i] < 0: del numbers[i] else: i += 1
B.numbers[:] = [x for x in numbers if x >= 0]
C.for num in numbers: if num < 0: numbers.remove(num)
D.for i in range(len(numbers)): if numbers[i] < 0: del numbers[i]
E.numbers = [x for x in numbers if x >= 0]
AnswersA, B

This while loop uses an index i. When a negative number is found, it deletes the element at i and does not increment i, so the next element shifts into the same index and is checked. When a non-negative number is found, i increments. This correctly removes all negatives in place while preserving order.

Why this answer

Both the while-loop with manual index management and the slice assignment using a list comprehension correctly modify the original list in place. The while loop carefully avoids skipping elements after deletion, and the slice assignment replaces the contents of the same list object. The other options either create a new list, cause iteration issues, or raise errors.

Exam trap

The trap here is assuming that iterating with for and removing elements is safe, when it actually skips elements due to shifting indices.

19
Multi-Selectmedium

Which THREE statements about the break statement in Python are correct? (Choose three.)

Select 3 answers
A.It can be used with an optional else clause.
B.It exits the innermost loop when executed.
C.It can be used in an if statement outside any loop.
D.If used inside a loop, it prevents the loop's else clause from executing.
E.It can be used only inside a for or while loop.
AnswersB, D, E

Correct: break terminates the innermost loop immediately.

Why this answer

The break statement, when executed inside a loop, immediately terminates the innermost loop it resides in, transferring control to the next statement after the loop. This is a fundamental behavior defined in Python's control flow documentation.

Exam trap

Python Institute often tests the misconception that break can be used with an optional else clause, confusing it with the loop-else construct, or that break can be used outside a loop, which leads to a SyntaxError.

20
MCQhard

A developer writes a recursive function to compute factorial, but it causes a RecursionError. Which of the following is the most likely cause?

A.The function returns a string instead of an integer
B.The function lacks a base case to stop recursion
C.The function modifies a global variable incorrectly
D.The function uses too many parameters
AnswerB

Without a base case, the factorial function calls itself indefinitely, exhausting the call stack until Python raises RecursionError. This satisfies the stem's scenario, since the missing terminating condition is the direct cause of unbounded recursive calls.

Why this answer

A recursive function must have a base case that stops further recursive calls. Without it, the function calls itself indefinitely until the recursion limit is exceeded, raising a RecursionError. In Python, the default recursion limit is 1000, and exceeding it triggers this error.

Exam trap

Python Institute often tests the concept that a missing base case is the direct cause of infinite recursion and RecursionError, not other common mistakes like incorrect return types or parameter issues.

How to eliminate wrong answers

Option A is wrong because returning a string instead of an integer would cause a TypeError (e.g., when trying to multiply an integer by a string), not a RecursionError. Option C is wrong because modifying a global variable incorrectly might lead to logical errors or unintended side effects, but it does not directly cause infinite recursion or a RecursionError. Option D is wrong because using too many parameters may cause a SyntaxError or performance issues, but it does not cause a RecursionError; recursion depth is independent of the number of parameters.

21
MCQeasy

What is the output of the code? numbers = [1, 2, 3, 4] result = [x**2 for x in numbers if x % 2 == 0] print(result)

A.[2, 4]
B.[4, 16]
C.[1, 9]
D.[2, 4, 16]
AnswerB

The comprehension filters to even values (2 and 4), then squares each, yielding 4 and 16. Odd elements 1 and 3 are excluded before the expression is applied, so the resulting list is [4, 16].

Why this answer

The list comprehension `[x**2 for x in numbers if x % 2 == 0]` iterates over `numbers`, filters for even numbers (2 and 4) using the condition `x % 2 == 0`, and squares each selected element. Squaring 2 gives 4, squaring 4 gives 16, so the result is `[4, 16]`. Option B is correct.

Exam trap

Python Institute often tests the distinction between the filter condition and the transformation expression, so the trap here is that candidates may confuse the filtered elements with the transformed output, leading them to pick the original even numbers (option A) or a mix (option D).

How to eliminate wrong answers

Option A is wrong because `[2, 4]` would be the result if the comprehension simply selected even numbers without squaring them (i.e., `[x for x in numbers if x % 2 == 0]`). Option C is wrong because `[1, 9]` corresponds to squaring the odd numbers (1 and 3), which would require the condition `if x % 2 != 0`. Option D is wrong because `[2, 4, 16]` incorrectly includes 2 (the original even number) and then 4 and 16 (the squares), suggesting a misunderstanding that the comprehension both keeps the original and applies the transformation.

22
MCQeasy

What is the output of the following code? for i in range(1, 6): if i == 3: continue print(i, end=' ')

A.1 2 3 4 5
B.1 2 4 5
C.1 2 4
D.1 2 3 4
AnswerB

When i equals 3, continue skips the remaining loop body, so print never executes for that value. The loop still iterates through 1 to 5, printing 1, 2, 4 and 5, each separated by a space via end=' '. Hence the output is 1 2 4 5.

Why this answer

The code uses a for loop with range(1, 6) and a continue statement when i == 3. When i equals 3, the continue skips the print(i, end=' ') statement, so 3 is not printed. The loop iterates through 1, 2, 4, and 5, producing the output '1 2 4 5'.

Exam trap

Python Institute often tests the `continue` statement by making candidates forget that it only skips the current iteration, not the entire loop, leading them to incorrectly omit subsequent values or include the skipped value.

How to eliminate wrong answers

Option A is wrong because it includes 3, which is skipped by the `continue` statement when `i == 3`. Option C is wrong because it omits 5, but the loop continues to the end of the range (5) after skipping 3. Option D is wrong because it includes 3 and omits 5, misunderstanding both the `continue` behavior and the loop's full range.

23
Multi-Selecthard

Which TWO of the following list operations modify the list in place?

Select 2 answers
A.mylist.sort()
B.mylist + [5]
C.mylist.copy()
D.mylist = mylist + [5]
E.mylist.append(5)
AnswersA, E

`mylist.sort()` reorders the existing list object directly, returning `None` rather than a new list. This satisfies the stem's requirement for in-place modification, since the original list's element order changes without rebinding the variable to a separate object.

Why this answer

`mylist.sort()` sorts the list in place, meaning it modifies the original list object without creating a new one. Option E is correct because `mylist.append(5)` adds the element 5 to the end of the list, directly mutating the original list object.

Exam trap

Python Institute often tests the difference between methods that mutate the list in place (like `sort()` and `append()`) versus operations that return a new list (like concatenation with `+` or `copy()`), trapping candidates who confuse reassignment with in-place modification.

24
Multi-Selecthard

Which TWO of the following code snippets will print the numbers 0, 1, 2, 3, 4?

Select 2 answers
A.for i in range(0,5): print(i)
B.for i in range(5+1): print(i)
C.for i in range(5): print(i)
D.for i in range(0,5,2): print(i)
E.for i in range(1,6): print(i)
AnswersA, C

The `range(0,5)` call generates integers from the start bound 0 up to, but excluding, the stop bound 5, yielding 0, 1, 2, 3, 4. Each value is bound to `i` and printed by the loop body, satisfying the stem's requirement to output exactly those five numbers in ascending order.

Why this answer

Option A is correct because range(0,5) generates the sequence 0,1,2,3,4 — starting at 0 and stopping before the exclusive end value 5 — so print(i) outputs exactly those numbers. Option C is correct because range(5) is equivalent to range(0,5), producing the same 0 through 4 sequence. Option B is wrong because range(5+1) equals range(6), which yields 0,1,2,3,4,5 and thus also prints 5.

Option D is wrong because range(0,5,2) uses a step of 2, producing only 0,2,4. Option E is wrong because range(1,6) starts at 1 and ends before 6, printing 1,2,3,4,5 instead of starting at 0.

Exam trap

Python Institute often tests the exclusive nature of the stop argument in `range()`, leading candidates to mistakenly think `range(5)` includes 5 or that `range(0,5)` includes 5, when in fact both produce 0 through 4.

25
MCQmedium

A program reverses a string using a while loop. The code is: text = "hello" reversed_text = "" index = len(text) - 1 while index > 0: reversed_text += text[index] index -= 1 print(reversed_text) It prints 'olle' instead of 'olleh'. What is the error?

A.Change the condition to 'while index >= 0:'
B.Change the initial index to len(text)
C.Use a for loop instead
D.Use string slicing: reversed_text = text[::-1]
AnswerA

The loop stops before processing index 0, so the character `'h'` is never appended. Changing the condition to `while index >= 0:` lets the final iteration run, appending `text[0]` and producing `'olleh'`. The off-by-one boundary in the loop guard is the sole defect.

Why this answer

The while loop condition `index > 0` stops when `index` becomes 0, so the character at index 0 (the first character 'h') is never appended to `reversed_text`. Changing the condition to `while index >= 0:` ensures the loop runs for index values from 4 down to 0 inclusive, producing the full reversed string 'olleh'.

Exam trap

Python Institute often tests off-by-one errors in while loops, where candidates mistakenly think `index > 0` covers all elements because they forget that the first index is 0, not 1.

How to eliminate wrong answers

Option B is wrong because setting the initial index to `len(text)` would cause an IndexError on the first iteration (index 5 is out of range for a 5-character string). Option C is wrong because using a for loop is not necessary; the while loop logic is correct except for the off-by-one condition, so switching to a for loop does not fix the root cause. Option D is wrong because while string slicing `text[::-1]` is a valid alternative, the question asks for the error in the given while loop code, not for a different implementation.

26
Multi-Selecthard

A Python programmer is reviewing a script that processes a list of order totals. The script must print each total that is greater than 100 and stop scanning entirely the first time it encounters a total of exactly 0. Which two statements about the loop logic are correct? (Choose two.)

Select 2 answers
A.Wrapping the loop in a try block and raising an exception at zero is the idiomatic way to stop iteration.
B.A break statement placed inside the loop immediately terminates the loop when the total equals 0.
C.An if statement comparing the total to 0, followed by break, correctly implements the early exit.
D.A continue statement placed inside the loop would stop the entire scan when the total equals 0.
E.The condition for printing must be checked before the zero check, or zero totals could be printed.
AnswersB, C

The break statement exits the innermost enclosing loop at once, skipping any remaining iterations. Placing it inside an if that checks for a total of exactly 0 fulfills the requirement to stop scanning entirely at that point. Any totals after the zero, whether above 100 or not, are never examined, which is precisely the behaviour the script must exhibit.

Why this answer

Stopping a scan at a sentinel value is the classic use case for break, which exits the innermost loop immediately. Pairing it with an if that compares the current total to 0 gives the required early termination. The continue statement only skips to the next iteration, and using exceptions for ordinary control flow is discouraged, so those approaches fail to meet the requirement.

Exam trap

The trap here is treating continue as a way to stop a loop, when it merely skips the remainder of the current iteration and keeps going.

27
MCQeasy

How many times will the following loop print 'Hi'? for i in range(3): print('Hi')

A.2
B.3
C.0
D.4
AnswerB

`range(3)` generates the integer sequence 0, 1, 2 — three values, starting at 0 and stopping before 3. The loop body executes once per generated value, so `print('Hi')` runs exactly three times, satisfying the stem's count of iterations.

Why this answer

The loop `for i in range(3):` iterates exactly three times because `range(3)` generates the sequence 0, 1, 2. Each iteration executes `print('Hi')`, so 'Hi' is printed three times. Option B is correct.

Exam trap

Python Institute often tests the off-by-one misconception where candidates think `range(3)` includes 3, leading them to choose 4 iterations, or they mistakenly count from 1 instead of 0.

How to eliminate wrong answers

Option A is wrong because it suggests the loop runs only twice, which would be the case for `range(2)` or a loop with a different stop value. Option C is wrong because the loop always executes at least once when the stop value is positive; `range(3)` is not empty. Option D is wrong because `range(3)` stops before 3, producing exactly three values, not four.

28
Multi-Selecthard

A developer is auditing loop constructs in a Python script. Which TWO statements about `break`, `continue`, `else`, and `range` are correct in Python? (Choose two.)

Select 2 answers
A.`break` exits only the current iteration and resumes with the next item.
B.A `while` loop always executes its body at least once, even if the condition is initially false.
C.`range(5)` produces the list `[0, 1, 2, 3, 4, 5]` when printed.
D.`continue` skips the rest of the current iteration and immediately re-evaluates the loop condition or fetches the next item.
E.A loop's `else` clause executes only if the loop finishes without hitting a `break`.
AnswersD, E

This correctly describes `continue`: it abandons the remaining statements in the current iteration and proceeds to the next one, re-checking the condition in a `while` loop or advancing the iterator in a `for` loop. It is often used to skip unwanted values without nesting the body inside a large `if` block, keeping the code flatter.

Why this answer

The `else` clause of a loop runs only on normal exhaustion, not after a `break`, which supports search idioms. `continue` ends the current iteration and moves to the next, re-evaluating or advancing as appropriate. The other statements misdescribe `break` as iteration-skipping, give `range` an inclusive upper bound, and claim `while` always runs once, all of which are incorrect for Python.

Exam trap

The trap here is assuming a loop's `else` runs regardless of how the loop ends, when a `break` actually suppresses it.

29
MCQhard

A data analyst has a list `readings` of numeric sensor values and needs to build a new list `scaled` that contains each reading multiplied by 2, but only for readings that are positive. Negative and zero readings should be excluded. Which code correctly produces `scaled`?

A.scaled = [r * 2 for r in readings if r >= 0]
B.scaled = [r * 2 for r in readings if r > 0]
C.scaled = [r * 2 if r > 0 for r in readings]
D.scaled = [r for r in readings if r > 0] * 2
AnswerB

This list comprehension applies the filter r > 0 before including an element and then multiplies each qualifying reading by 2. Negative and zero values are excluded by the condition, and only positive readings appear in the new list. It is concise, correct, and uses standard Python list comprehension syntax with a filter clause.

Why this answer

The correct comprehension uses a filter clause after the for to include only positive readings, then multiplies each by 2 in the expression. This produces a new list containing doubled values for positive readings only, excluding negatives and zeros. It matches the analyst's specification and uses idiomatic Python syntax.

Exam trap

The trap here is mixing up the filter condition with the transformation, or using >= instead of >, which would incorrectly include zero readings.

30
MCQmedium

A validation script defines a list named flags containing boolean values. The script must determine whether every flag is True and print 'All clear' only in that case; otherwise it should print 'Check needed'. Which code fragment implements this logic correctly?

A.if flags: print('All clear') else: print('Check needed')
B.if any(flags): print('All clear') else: print('Check needed')
C.if all(flags): print('All clear') else: print('Check needed')
D.if flags == True: print('All clear') else: print('Check needed')
AnswerC

The built-in all function returns True when every element in the iterable is truthy. For a list of booleans, that means all values must be True, so the conditional prints the correct message for both the all-True and any-False cases.

Why this answer

Determining that every element is True requires a check that inspects all elements and fails if any is falsy. The built-in all function does exactly that, returning True only when every element is truthy and False otherwise, which maps directly onto the two required messages.

Exam trap

The trap here is confusing any with all or assuming that a non-empty list of booleans is itself a reliable truth test for all values being True.

31
MCQmedium

A software tester is examining a list of error codes: `errors = [404, 500, 403, 404, 200]`. She wants to determine if the code 404 appears in the list and print 'Found' if it does, otherwise 'Not found'. Which code correctly achieves this?

A.if errors.count(404) == 0: print('Found') else: print('Not found')
B.if errors in 404: print('Found') else: print('Not found')
C.if 404 in errors: print('Found') else: print('Not found')
D.if errors.index(404): print('Found') else: print('Not found')
AnswerC

The `in` operator checks membership in a list. If 404 is present, it prints 'Found'; otherwise, 'Not found'. Since 404 is in the list, it prints 'Found'. This is the simplest and most direct way to test for presence.

Why this answer

The `in` operator is the correct tool for checking if an element exists in a list. It returns a boolean and does not raise errors. The other options either misuse the `in` operator, rely on `index()` which can raise exceptions and misinterpret index 0, or invert the logic with `count()`.

Exam trap

The trap here is using `index()` or `count()` for membership testing, which can lead to incorrect results or exceptions when the value is at index 0 or absent.

32
MCQhard

A monitoring script checks a list of sensor readings and must stop examining them as soon as a reading above 100 is found, without checking any remaining readings. The readings list contains at least one value above 100. Which loop control approach implements this behavior correctly?

A.Use pass when a reading exceeds 100, so the loop silently ignores the condition and finishes normally.
B.Use continue when a reading exceeds 100, so the loop skips the rest of that iteration and keeps going.
C.Use break when a reading exceeds 100, so the loop ends immediately and no further readings are checked.
D.Use else on the for loop, so the loop stops when a reading exceeds 100.
AnswerC

break terminates the innermost enclosing loop at once, so as soon as a reading greater than 100 appears, no subsequent readings are examined. That exactly matches the requirement to stop early. Execution resumes at the first statement after the loop, where the script can act on the detected condition.

Why this answer

Only break exits a loop immediately when a condition is met. When a reading above 100 is encountered, break ends iteration and control moves past the loop, so no later readings are examined. The other keywords either skip one iteration, do nothing, or run after normal completion.

Exam trap

The trap here is treating continue as a way to stop the loop, when it only skips the current iteration and keeps iterating.

33
MCQeasy

During a lab exercise, a student writes the following code to print a countdown from 3 down to 1, but the code enters an infinite loop and never stops. The code is: count = 3 while count > 0: print(count) Which change makes the loop terminate after printing 3, 2, and 1?

A.Add the statement count = count + 1 inside the loop body.
B.Add the statement count = count - 1 inside the loop body.
C.Change the condition to while count < 0:
D.Add the statement count += 0 inside the loop body.
AnswerB

Decrementing count each pass changes the value from 3 to 2 to 1, and after printing 1 it becomes 0, making count > 0 false and ending the loop. This is the standard counter-controlled pattern, where the loop variable must be updated inside the body so the condition eventually fails and the program continues.

Why this answer

A while loop repeats as long as its condition stays true, so the counter must move toward the exit value on each pass. Reducing count by one each iteration makes the sequence 3, 2, 1 and then 0, at which point the condition fails and execution continues after the loop. Without such an update the condition never changes.

Exam trap

The trap here is assuming the loop condition alone controls termination, when an unchanged loop variable leaves the condition permanently true.

34
Drag & Dropmedium

Arrange the steps to install a third-party Python package using pip.

Drag or tap steps into the slots.

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

Why this order

Installing packages with pip involves checking pip, running install, and verifying.

35
MCQmedium

A company uses a for loop to iterate over a list of transaction amounts. They want to skip negative amounts. Which statement inside the loop correctly achieves this?

A.if amount < 0: amounts.remove(amount)
B.if amount < 0: break
C.if amount < 0: pass
D.if amount < 0: continue
AnswerD

The continue statement immediately ends the current iteration and returns control to the loop header, so the negative amount is never processed. Placing it under 'if amount < 0' skips only negative values while all non-negative amounts still execute.

Why this answer

The `continue` statement immediately jumps to the next iteration of the loop, skipping any remaining code in the current iteration. When `amount < 0`, the loop will not process that negative transaction and will move to the next element in the list, effectively skipping negative amounts.

Exam trap

Python Institute often tests the distinction between `break`, `continue`, and `pass`, and the trap here is that candidates confuse `break` (which exits the loop) with `continue` (which skips to the next iteration), or think `pass` is a valid way to skip code when it actually does nothing.

How to eliminate wrong answers

Option A is wrong because `amounts.remove(amount)` modifies the list while iterating over it, which can lead to skipped elements or index errors due to the list's size changing during iteration. Option B is wrong because `break` terminates the entire loop prematurely, stopping all further iteration even for positive amounts after the first negative one. Option C is wrong because `pass` is a no-op that does nothing; it simply continues execution to the next line, so negative amounts would still be processed.

36
Multi-Selectmedium

Which THREE of the following are valid ways to create a list with elements 10, 20, 30?

Select 3 answers
A.my_list = [x for x in (10,20,30)]
B.my_list = list((10, 20, 30))
C.my_list = list(10, 20, 30)
D.my_list = [10; 20; 30]
E.my_list = [10, 20, 30]
AnswersA, B, E

The list comprehension iterates over the tuple (10,20,30) and appends each element, producing a new list containing exactly those three values. It is a valid construction, though more verbose than a literal, and yields the required elements in order.

Why this answer

Option A is correct because a list comprehension iterating over the tuple (10,20,30) produces a new list [10, 20, 30]. Option B is correct because list((10, 20, 30)) converts the tuple into a list with those three elements. Option E is correct because a list literal [10, 20, 30] directly creates the desired list.

Option C is invalid because list() accepts at most one iterable argument, so list(10, 20, 30) raises a TypeError. Option D is invalid because semicolons are not valid separators inside a Python list literal; elements must be comma-separated.

Exam trap

In multi-select questions, carefully evaluate each option against the stem without reading in extra constraints. The question simply asks for valid ways to create a specific list; do not assume that a literal assignment is excluded unless explicitly stated. Be cautious about the number of correct answers: ensure you select all that apply, especially when the stem specifies a count.

37
MCQeasy

A company maintains a list of employee names. They want to check if 'Alice' is in the list. Which of the following is the most Pythonic way to achieve this?

A.employees.contains('Alice')
B.for name in employees: if name == 'Alice': found = True; break
C.if employees.index('Alice') != -1:
D.if 'Alice' in employees:
AnswerD

The 'in' operator performs a membership test directly against the list, returning a Boolean without indexing or looping. Writing 'if "Alice" in employees:' is the idiomatic, readable Pythonic form, avoiding alternatives like index() or manual iteration that add unnecessary complexity.

Why this answer

The most Pythonic way because it uses the `in` operator, which directly checks membership in a list with a single, readable expression. This approach is idiomatic Python, leveraging the language's built-in support for membership testing without manual iteration or exception handling.

Exam trap

Python Institute often tests the distinction between Python's `in` operator and methods from other languages (like `contains()`), or the incorrect assumption that `.index()` returns -1 on failure, which is a common trap for candidates coming from languages like Java or C++.

How to eliminate wrong answers

Option A is wrong because Python lists do not have a `contains()` method; this is a Java-style method name, not valid in Python. Option B is wrong because while the loop works, it is verbose and non-idiomatic; Python's `in` operator is the preferred, concise way to test membership. Option C is wrong because `list.index()` raises a `ValueError` if the item is not found, not returning -1; using it for membership testing is both incorrect and inefficient.

38
MCQmedium

A programmer is writing a script to process a list of sensor readings. The script should stop processing as soon as a reading of 0 is encountered. Which statement should be placed inside the loop to achieve this?

A.exit
B.break
C.pass
D.continue
AnswerB

The `break` statement immediately terminates the innermost enclosing loop. When a sensor reading of 0 is detected, using `break` will exit the loop entirely, preventing further processing of remaining readings. This matches the requirement to stop processing as soon as the condition is met.

Why this answer

To stop a loop immediately when a condition is met, the `break` statement is used. It transfers control to the statement immediately following the loop. The `continue` statement would only skip the current iteration, while `pass` does nothing and `exit` is not a valid loop control statement.

Exam trap

The trap here is confusing `break` with `continue`; `break` exits the loop entirely, while `continue` only skips the current iteration.

39
MCQmedium

A programmer is building a simple inventory tracker using a Python list named stock that contains integer quantities. They need to add 10 to every quantity in the list, modifying the list in place. Which code correctly performs this operation?

A.stock = [qty + 10 for qty in stock]
B.stock = stock + 10
C.for qty in stock: qty = qty + 10
D.for i in range(len(stock)): stock[i] = stock[i] + 10
AnswerD

Iterating over indices with range(len(stock)) allows direct assignment to each element via stock[i], which modifies the list in place. This is the standard pattern for updating every element when you need to change the original list. The other approaches either do not modify the list or produce incorrect results.

Why this answer

To modify a list in place, you must assign to individual elements using their indices. Using range(len(stock)) provides those indices, and stock[i] = stock[i] + 10 updates each element. The other options either leave the list unchanged, create a new list, or cause an error, so they do not satisfy the in-place requirement.

Exam trap

The trap here is assuming that modifying the loop variable modifies the list, when actually it only rebinds the variable to a new value.

40
MCQeasy

A developer is writing a Python script to validate a list of usernames. The script must examine each username in the list and print 'Invalid' as soon as a username shorter than 3 characters is found, then stop checking the remaining usernames. Which control flow statement should be used inside the loop to terminate it immediately when the invalid username is encountered?

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

The break statement immediately terminates the innermost loop, so once a short username is found, the loop exits and no further usernames are checked. This matches the requirement to stop checking as soon as an invalid entry is detected, making it the correct control flow statement for early termination inside the loop.

Why this answer

The break statement exits the innermost loop immediately, which is exactly what is needed to stop checking usernames once an invalid one is found. The other statements either skip only one iteration, do nothing, or exit the whole function, so they do not satisfy the requirement to terminate the loop early while continuing the rest of the script.

Exam trap

The trap here is confusing continue with break, leading to skipping only the current item instead of stopping the entire loop.

41
MCQeasy

A developer needs to iterate over a list named `colors` and print each color on a separate line. Which code snippet correctly accomplishes this?

A.for (color in colors): print(color)
B.for color in colors: print(color)
C.for color in colors print(color)
D.for color in colors: print(color)
AnswerD

This is the correct syntax for a for loop in Python. The loop variable `color` takes each value from the list `colors` one at a time, and `print(color)` outputs it. This is the most straightforward and idiomatic way to iterate over a list and perform an action for each element.

Why this answer

The correct way to iterate over a list and print each element is to use a for loop with proper indentation and a colon at the end of the loop header. The loop variable takes each element from the list in turn, and the indented block executes for each element. This pattern is fundamental in Python for processing sequences.

Exam trap

The trap here is forgetting the colon at the end of the for statement or misindenting the loop body, which are common syntax errors for beginners.

42
MCQhard

A developer is building a simple inventory check. The list stock holds integers representing item quantities. He wants to append the string 'low' to a separate list alerts once for each quantity that is less than 5. Which code correctly populates alerts?

A.for q in stock: if q < 5: alerts.append('low')
B.if any(q < 5 for q in stock): alerts.append('low')
C.alerts = ['low' for q in stock if q < 5] appended to the existing alerts list.
D.for q in stock: if q < 5: alerts.append('low') break
AnswerA

This loop visits every quantity in stock, tests whether it is below 5, and appends 'low' to alerts each time the test succeeds. Because the append is inside the if but inside the loop, the string is added once per qualifying quantity, and the number of entries in alerts matches the count of low quantities, which is exactly what the developer needs.

Why this answer

Appending inside a loop with a conditional adds one entry per qualifying quantity, which matches the requirement of one 'low' per item below 5. Breaking after the first match stops too early, using any collapses the count to a single Boolean decision, and rebinding alerts with a comprehension replaces rather than extends the existing list.

Exam trap

The trap here is placing break after the append, which looks like it just stops checking but actually prevents any later low quantities from being recorded.

43
MCQeasy

A developer writes a while loop to count down from 10 to 1 and then stop. Which condition should be used?

A.while counter != 0:
B.while counter >= 0:
C.while counter < 10:
D.while counter > 0:
AnswerD

With counter starting at 10 and decrementing, the loop must continue while counter remains above zero, so counter > 0 keeps iterations running for values 10 down to 1 and terminates once counter reaches 0, preventing an extra countdown iteration.

Why this answer

The while loop must continue as long as the counter is greater than 0, counting down from 10 to 1. When counter becomes 0, the condition `counter > 0` evaluates to False, and the loop terminates, stopping exactly at 1.

Exam trap

Python Institute often tests the off-by-one error where candidates choose `>= 0` thinking they need to include 0, but the requirement to stop at 1 means the loop must not execute when counter is 0.

How to eliminate wrong answers

Option A is wrong because `while counter != 0:` would cause the loop to continue until counter becomes 0, but if counter starts at 10 and decrements, it will reach 0 and stop correctly; however, this condition is less intuitive and could cause an infinite loop if counter skips 0 (e.g., decrement by 2). Option B is wrong because `while counter >= 0:` would include 0, causing the loop to run one extra iteration when counter is 0, printing 0 instead of stopping at 1. Option C is wrong because `while counter < 10:` would start as True (since 10 < 10 is False) and never execute the loop body, or if counter starts below 10, it would count up, not down.

44
MCQeasy

A game developer writes a loop to process a list of player scores: `scores = [45, 82, 67, 91]`. She wants to print only the scores that are greater than 80. Which loop correctly accomplishes this?

A.for score in scores: if score < 80: print(score)
B.for score in scores: if score >= 80: print(score)
C.for score in scores: if score > 80: print(score)
D.for score in scores: print(score) if score > 80: break
AnswerC

This loop iterates over each score, and the `if` statement filters those greater than 80. It will print 82 and 91. This is the straightforward way to apply a condition inside a loop and print matching elements.

Why this answer

To print only scores greater than 80, the loop must iterate over all scores and use an `if` statement with the `>` operator to print those that satisfy the condition. The correct snippet does exactly that, printing 82 and 91. Other options use incorrect comparison operators or misplaced print statements.

Exam trap

The trap here is mixing up the comparison operators `>` and `<`, or using `>=` which includes the boundary value when the requirement is strictly greater.

45
MCQeasy

A developer is writing a Python script that must iterate over the characters of the string stored in variable `word` and print each character on its own line, without using index numbers. Which of the following loops accomplishes this?

A.while word: print(word)
B.for ch in word.split(): print(ch)
C.for ch in word: print(ch)
D.for ch in range(len(word)): print(ch)
AnswerC

This is correct because a Python `for` loop directly iterates over any iterable, and a string is an iterable that yields one character per iteration. Each pass binds `ch` to the next character and prints it, producing one character per line in order. No index counter or range is needed, which is the idiomatic and simplest solution for this scenario.

Why this answer

A Python `for` loop iterates directly over any iterable object, and strings are iterables that produce their characters one at a time. Binding each character to a loop variable and printing it yields exactly one character per line in the original order. The remaining constructs either iterate over numeric indexes, never advance the loop variable, or split the string into words rather than characters.

Exam trap

The trap here is assuming a `for` loop over a string needs `range()` and indexing, when the string itself is already directly iterable.

46
Multi-Selectmedium

A programmer is reviewing code that uses loops and conditional statements. Which TWO of the following statements about Python control flow are correct? (Choose two.)

Select 2 answers
A.An if statement can be nested inside a for loop, and a for loop can be nested inside an if statement.
B.A while loop always executes its body at least once, even if the condition is initially false.
C.The break statement can be used outside a loop to terminate the program.
D.The else clause of a for loop executes only if the loop completes without encountering a break.
E.The continue statement exits the current loop entirely and resumes execution after the loop.
AnswersA, D

Python allows arbitrary nesting of control structures. An if can appear inside a for body, and a for can appear inside an if body, as long as indentation is correct. This flexibility enables complex logic, such as filtering items with if and then iterating over a subset with for, or vice versa.

Why this answer

The two correct statements are that a for loop's else runs only without a break, and that control structures can be nested arbitrarily. These reflect Python's actual semantics. The other statements mischaracterize continue, break, and while loop behavior, each of which is well-defined and different from the described behavior.

Exam trap

The trap here is mixing up continue and break, or assuming that while loops always execute at least once as in some other languages.

47
MCQeasy

A programmer wants to create a list of even numbers from 0 to 10 inclusive. Which list comprehension is correct?

A.[x for x in range(0,11) if x%2==0]
B.[x for x in range(0,10) if x%2==0]
C.[x for x in range(0,11) if x%2]
D.[x for x in range(0,11) if x%2==1]
AnswerA

The comprehension iterates over `range(0,11)`, whose stop value is exclusive, so it yields 0 through 10 inclusive as the stem requires. The filter `x%2==0` then retains only even values, producing `[0,2,4,6,8,10]` in a single expression without needing an explicit append loop.

Why this answer

It uses `range(0,11)` to generate numbers from 0 to 10 inclusive, and the condition `if x%2==0` selects only even numbers (where the remainder when divided by 2 is 0). This matches the requirement exactly.

Exam trap

Python Institute often tests the distinction between `range(0,11)` and `range(0,10)` to catch candidates who forget that the stop value is exclusive, and the use of truthy/falsy values in conditions (e.g., `if x%2` instead of `if x%2==0`) to confuse even vs. odd selection.

How to eliminate wrong answers

Option B is wrong because `range(0,10)` generates numbers from 0 to 9, missing the number 10, so it does not include 10 as required. Option C is wrong because `if x%2` evaluates to True for odd numbers (since any non-zero remainder is truthy), so it selects odd numbers instead of even numbers. Option D is wrong because `if x%2==1` also selects odd numbers (remainder 1), not even numbers.

48
Multi-Selecthard

Which TWO of the following are true about Python's if statement?

Select 2 answers
A.if statements cannot be nested.
B.An if statement must have a corresponding else clause.
C.An if statement can have multiple elif blocks.
D.The condition can be any expression; e.g., a non-zero integer is considered True.
E.The condition must be enclosed in parentheses.
AnswersC, D

Python allows multiple elif clauses.

Why this answer

Python's if statement allows multiple elif blocks to check additional conditions after the initial if condition. This enables a chain of conditional checks, and each elif is evaluated only if all previous conditions were False. The elif clause is a contraction of 'else if' and is a unique feature of Python's syntax.

Exam trap

The Python Institute often tests the misconception that parentheses are required around the condition in Python, which is a carryover from languages like C or Java, but Python uses indentation and colons instead of parentheses for control flow syntax.

49
MCQmedium

Which list method modifies the list in place by adding all elements of another iterable to the end?

A.+ operator
B.insert()
C.append()
D.extend()
AnswerD

extend() appends every element from an iterable individually to the existing list, mutating it in place and returning None. append() adds the iterable as one nested object, while + and slicing create new lists, so extend() uniquely satisfies the in-place, element-wise requirement.

Why this answer

The `extend()` method modifies the list in place by appending all elements from the provided iterable (e.g., another list, tuple, or string) to the end. It does not return a new list; it mutates the original list directly, which is the behavior described in the question.

Exam trap

Python Institute often tests the distinction between `append()` and `extend()` — the trap is that candidates confuse adding an iterable as a single element (append) with adding its individual elements (extend), especially when the iterable is a list or string.

How to eliminate wrong answers

Option A is wrong because the `+` operator creates a new list by concatenating two lists, leaving the original lists unchanged — it does not modify a list in place. Option B is wrong because `insert()` adds a single element at a specified index, not all elements of an iterable to the end. Option C is wrong because `append()` adds its argument as a single element (even if it is an iterable) to the end of the list, not the individual elements of an iterable.

50
MCQhard

A developer needs to check if all elements in a list of integers are even. Which code correctly implements this?

A.all_even = all(num % 2 for num in mylist)
B.all_even = any(num % 2 == 0 for num in mylist)
C.all_even = True for num in mylist: if num % 2 != 0: all_even = False break
D.all_even = False for num in mylist: if num % 2 == 0: all_even = True else: all_even = False
AnswerC

Correctly breaks on first odd.

Why this answer

It initializes `all_even` to `True`, then iterates through the list. If any element is odd (`num % 2 != 0`), it sets `all_even` to `False` and breaks out of the loop early, which is an efficient and correct way to check that all elements are even.

Exam trap

Python Institute often tests the misconception that `all()` with a condition like `num % 2` checks for even numbers, when in fact it checks for truthy remainders (odd numbers), leading candidates to incorrectly select Option A.

How to eliminate wrong answers

Option A is wrong because `all(num % 2 for num in mylist)` checks if every remainder is truthy (non-zero), which would be True only if all numbers are odd, not even. Option B is wrong because `any(num % 2 == 0 for num in mylist)` returns True if at least one element is even, not if all are even. Option D is wrong because it sets `all_even` to `True` whenever it encounters an even number, but then resets it to `False` on an odd number; however, if the list contains only even numbers, it will remain `True` only if the last element is even, but the logic is flawed because it does not break early and incorrectly handles the flag — for example, with `[2, 4, 6]` it works, but with `[2, 3, 4]` it ends as `False` (correct), but the approach is inefficient and conceptually incorrect because it toggles the flag on every element rather than checking the invariant.

51
MCQeasy

Which code correctly creates a list of squares for numbers 1 to 5 using a list comprehension?

A.squares = [x**2 for x in range(5)]
B.squares = [x^2 for x in (1,2,3,4,5)]
C.squares = [x**2 for x in range(1,6)]
D.squares = [x^2 for x in [1,2,3,4,5]]
AnswerC

The comprehension iterates x over range(1,6), yielding 1 through 5 inclusive, and squares each value with the ** operator. This satisfies the stem's requirement of numbers 1 to 5, since range's stop argument is exclusive; range(1,5) would omit 25.

Why this answer

It uses the proper syntax for a list comprehension: `[expression for item in iterable]`. Here, `x**2` computes the square, and `range(1,6)` generates numbers 1 through 5 (since range excludes the stop value). This produces the list `[1, 4, 9, 16, 25]`.

Exam trap

Python Institute often tests the distinction between `**` (exponentiation) and `^` (bitwise XOR), as well as the correct use of `range()` boundaries, to catch candidates who confuse operators or off-by-one errors.

How to eliminate wrong answers

Option A is wrong because `range(5)` generates numbers 0 through 4, not 1 through 5, so the list would include `0**2 = 0` and miss `5**2 = 25`. Option B is wrong because `x^2` uses the bitwise XOR operator, not exponentiation, so it computes `x XOR 2` instead of `x**2`. Option D is wrong because `x^2` again uses the bitwise XOR operator, not exponentiation, and although the iterable is correct, the operation is incorrect.

52
MCQhard

A data analyst maintains `matrix = [[1, 2], [3, 4], [5, 6]]` and wants a flat list `flat` containing every number in row order, that is `[1, 2, 3, 4, 5, 6]`. Which code produces this result?

A.flat = [] for row in matrix: flat.append(row)
B.flat = [] for row in matrix: for value in row: flat.append(value)
C.flat = matrix[0] + matrix[1] + matrix[2]
D.flat = [] for i in range(len(matrix)): flat.append(matrix[i][0])
AnswerB

The nested loops first take each inner list as `row`, then iterate that row to visit every integer, appending each to `flat`. Processing rows in order and values within each row in order yields exactly `[1, 2, 3, 4, 5, 6]`. This is the standard, explicit way to flatten a two-dimensional list and works for rows of differing lengths as well.

Why this answer

Flattening a list of lists requires iterating the outer list to obtain each row and then iterating each row to reach its elements. Appending every visited integer builds the one-dimensional result in the original order. Appending whole rows keeps the nesting, hard-coded concatenation does not adapt to different sizes, and selecting a single column index drops data.

Exam trap

The trap here is appending the inner list itself instead of iterating it, which keeps the data nested.

53
MCQhard

A programmer has a list of tuples representing (product, price) and wants to find the highest price. Which code correctly finds the maximum price?

A.max_price = max(prices, key=lambda x: x[1])
B.max_price = max([price for product, price in prices])
C.max_price = 0; for p in prices: if p[1] > max_price: max_price = p[1]
D.max_price = sorted(prices, key=lambda x: x[1])[-1]
AnswerB

Correct; list comprehension extracts prices, then max finds the largest.

Why this answer

Ly uses a list comprehension to extract all prices from the tuples, then passes that list to the built-in `max()` function, which returns the highest numeric value. This directly solves the problem of finding the maximum price without any unnecessary complexity.

Exam trap

Python Institute often tests the difference between `max()` returning the element that maximizes the key versus returning the key value itself, leading candidates to incorrectly choose option A when they want just the price.

How to eliminate wrong answers

Option A is wrong because `max(prices, key=lambda x: x[1])` returns the entire tuple with the highest price, not just the price itself. Option C is wrong because it initializes `max_price` to 0, which will fail if all prices are negative (the maximum would remain 0 instead of the actual highest negative price). Option D is wrong because `sorted(prices, key=lambda x: x[1])[-1]` returns the entire tuple with the highest price, not just the price value.

54
MCQhard

What is the output of the following code? numbers = [1, 2, 3, 4, 5] total = 0 for i in numbers: if i % 2 == 0: continue total += i print(total)

A.10
B.8
C.6
D.9
AnswerD

The loop skips even values via continue, so only odd numbers accumulate: 1 + 3 + 5 = 9. Even numbers 2 and 4 are excluded before total += i executes, and the final print outputs 9.

Why this answer

The exhibit shows code that iterates over the list [1, 2, 3, 4, 5] and uses `if i % 2 == 0: continue` to skip even numbers. Only odd numbers (1, 3, 5) are summed, giving 1 + 3 + 5 = 9. Therefore, option D is correct.

Exam trap

Python Institute often tests the `continue` statement by embedding it inside a conditional that filters out specific values, leading candidates to mistakenly sum all elements or incorrectly include the skipped values.

How to eliminate wrong answers

Option A is wrong because 10 would be the sum of all numbers in the list (1+2+3+4+5), but the `continue` statement skips even numbers, so not all numbers are added. Option B is wrong because 8 would be the sum if only the number 2 was skipped (1+3+4+5=13) or if a different condition was used, but the code skips both 2 and 4. Option C is wrong because 6 would be the sum of only the even numbers (2+4), but the code adds odd numbers, not even numbers.

55
MCQeasy

A Python developer is writing a program that prompts the user to enter a positive integer. The program should repeatedly ask for input until the user enters a number greater than zero. Which loop construct is most appropriate to implement this requirement?

A.for loop with a range
B.while loop with a condition
C.if statement with a break
D.do-while loop
AnswerB

A while loop repeatedly executes a block of code as long as a specified condition remains true. In this scenario, the condition can be set to continue prompting while the entered number is not greater than zero. This allows the loop to run until the user provides valid input, making it the ideal choice for indefinite repetition.

Why this answer

The requirement is to repeatedly prompt the user until a positive integer is entered. This calls for a loop that continues based on a condition that depends on user input. A while loop is designed for such indefinite iteration, as it checks the condition before each iteration and can be controlled by the input value.

Other constructs either cannot repeat indefinitely or do not exist in Python.

Exam trap

The trap here is assuming Python has a do-while loop like some other languages, or confusing the role of if and break with a loop.

56
MCQmedium

Which of the following best describes the behavior of the 'range' function in a for loop?

A.It generates a sequence of numbers from start to stop exclusive
B.It returns a list of numbers with a default step of 0
C.It can only be used with integers
D.It generates a list of numbers from start to stop inclusive
AnswerA

range(start, stop) produces integers beginning at start and stopping before stop, so the stop value is excluded from the sequence. The step argument defaults to one. This exclusive upper bound is the defining behaviour tested, distinguishing it from inclusive iteration constructs.

Why this answer

The built-in `range()` function in Python generates an immutable sequence of numbers from the start value (default 0) up to, but not including, the stop value. When used in a `for` loop, it yields each number in the sequence one at a time, making it ideal for iterating a fixed number of times. The stop value is exclusive, meaning the loop body does not execute for the stop value itself.

Exam trap

Python Institute often tests the misconception that `range()` returns a list or that the stop value is inclusive, leading candidates to pick option D, but in Python, `range()` returns a lazy sequence and the stop value is always exclusive.

How to eliminate wrong answers

Option B is wrong because the default step of `range()` is 1, not 0; a step of 0 would cause a `ValueError`. Option C is wrong because `range()` can accept integer arguments only, but it can also be used with negative integers and zero, and the step can be negative; however, it strictly requires integers, not floats. Option D is wrong because `range()` generates numbers from start to stop exclusive, not inclusive; the stop value is never included in the sequence.

57
Multi-Selectmedium

Which two of the following statements about Python lists are true?

Select 2 answers
A.Lists are immutable.
B.List elements can be accessed using negative indices.
C.The append() method inserts an element at the beginning of the list.
D.The len() function returns the number of elements in a list.
E.Lists can only contain elements of the same data type.
AnswersB, D

Negative indices start from -1 for the last element.

Why this answer

Python lists support negative indexing, where -1 refers to the last element, -2 to the second last, and so on. This allows convenient access to elements from the end of the list without needing to calculate the length.

Exam trap

Python Institute often tests the misconception that lists are immutable (confusing them with tuples) or that append() inserts at the beginning (confusing it with insert(0, ...)), and candidates may also incorrectly assume lists are homogeneous like arrays in some other languages.

58
MCQmedium

A teacher writes a program that must print each student name from a list called roster on its own line, but stop printing entirely as soon as the name "STOP" is encountered, without printing "STOP" itself. Which loop body achieves this?

A.for name in roster: while name != "STOP": print(name) break
B.for name in roster: if name == "STOP": break print(name)
C.for name in roster: print(name) if name == "STOP": break
D.for name in roster: if name == "STOP": continue print(name)
AnswerB

The condition is checked before printing, so when STOP is reached the break statement exits the loop immediately and the print call is skipped for that iteration. Every name before STOP prints on its own line, and no further iterations run, exactly matching the teacher's requirement to halt without printing the sentinel value.

Why this answer

Placing the sentinel comparison before the print call and using break ensures the loop terminates at the first occurrence of "STOP" without emitting that value. Checking after printing would leak the sentinel into the output, and using continue would skip only one element while later names still print, so only the pre-check with break satisfies both conditions.

Exam trap

The trap here is assuming continue and break behave the same, when continue only skips one iteration instead of ending the loop.

59
MCQhard

A data analyst writes a Python script to double each element in a matrix without altering the original. The code is: original = [[1,2,3],[4,5,6]] copy = original for i in range(len(original)): for j in range(len(original[i])): copy[i][j] *= 2 print(original) The output shows [[2,4,6],[8,10,12]], meaning the original was also changed. Which single modification to the line 'copy = original' ensures the original matrix remains unchanged?

A.Replace `copy = original` with `copy = original[:]`
B.Replace `copy = original` with `import copy; copy = copy.deepcopy(original)`
C.Replace `copy = original` with `copy = list(original)`
D.Replace the nested loop with a list comprehension: `copy = [[x*2 for x in row] for row in original]`
AnswerB

Plain assignment binds both names to the same nested list, so mutating copy also mutates original. copy.deepcopy recursively duplicates every inner list, giving independent objects and satisfying the requirement that the original matrix stays unchanged.

Why this answer

`copy.deepcopy()` creates a fully independent copy of the nested list structure. In Python, assignment (`copy = original`) only copies the reference to the outer list, so modifying elements through `copy` also modifies `original`. Shallow copies (like `original[:]` or `list(original)`) copy the outer list but still share references to the inner lists, so changes to inner elements affect both.

Only `deepcopy` recursively duplicates all nested objects, ensuring the original matrix remains unchanged.

Exam trap

Python Institute often tests the distinction between shallow and deep copy in nested structures, and the trap here is that candidates assume `original[:]` or `list(original)` create a full independent copy, not realizing that inner lists are still shared references.

How to eliminate wrong answers

Option A is wrong because `original[:]` creates a shallow copy of the outer list; the inner lists are still shared references, so modifying `copy[i][j]` still alters `original[i][j]`. Option C is wrong because `list(original)` also performs a shallow copy, producing a new outer list but reusing the same inner list objects, so the original matrix is still mutated. Option D is wrong because it replaces the entire loop with a list comprehension that builds a new matrix without modifying `original`, but the question asks for a modification to the line `copy = original`, not to the loop; this option changes the loop structure, not the assignment, and thus does not satisfy the requirement.

60
MCQhard

A Python developer is writing a function that takes a list of numbers and returns a new list containing only the numbers that are divisible by 3 or 5. The developer writes the following code: def filter_numbers(nums): result = [] for n in nums: if n % 3 == 0 or n % 5 == 0: result.append(n) return result Which statement about this function is true?

A.The function correctly returns numbers divisible by 3 or 5, but it will raise an error if the list contains a zero.
B.The function correctly returns numbers divisible by 3 or 5, but it includes duplicates if the input list has duplicates.
C.The function correctly returns numbers divisible by 3 or 5, and it does not modify the original list.
D.The function correctly returns numbers divisible by 3 or 5, but it uses a logical OR when it should use a logical AND to meet the requirement.
AnswerC

The function creates a new list called result and appends qualifying numbers to it. It does not alter the original list nums in any way. The filtering condition using modulo and logical OR correctly identifies numbers divisible by 3 or 5. Thus, this statement is true and accurately describes the function's behavior.

Why this answer

The function iterates over the input list, checks each number for divisibility by 3 or 5 using the modulo operator and logical OR, and appends qualifying numbers to a new list. It does not modify the original list, and it correctly implements the specified filtering. The other statements are either incorrect or describe behavior that does not occur.

Exam trap

The trap here is thinking that testing zero with modulo raises an error, or misinterpreting the logical operator requirement.

61
MCQmedium

A quality-control engineer stores defect codes in a list `codes` and wants to print each code until a sentinel value `'STOP'` is encountered, at which point the loop should end without printing `'STOP'`. Which loop correctly achieves this behavior?

A.for c in codes: if c == 'STOP': continue print(c)
B.for c in codes: if c == 'STOP': break print(c)
C.for c in codes: while c != 'STOP': print(c)
D.for c in codes: print(c) if c == 'STOP': break
AnswerB

This loop iterates over the codes, checks for the sentinel before printing, and breaks immediately when 'STOP' appears. Because the break occurs before the print statement, 'STOP' itself is never printed. It meets the requirement of printing each code until the sentinel and then terminating the loop cleanly.

Why this answer

The correct loop checks each element for the sentinel before any output and uses break to exit the entire loop. Placing the break before the print ensures the sentinel is never displayed, and break ends iteration immediately so no later codes are processed. This matches the engineer's requirement precisely.

Exam trap

The trap here is confusing break with continue, or placing the print before the sentinel check so the sentinel is printed despite the intention to stop before it.

62
MCQmedium

A Python programmer is working with a list of strings called words. The programmer wants to create a new list that contains the lengths of each word, but only for words that have more than three characters. Which code snippet correctly produces this list?

A.lengths = [len(word) for word in words if len(word) > 3]
B.lengths = [] for word in words: if len(word) > 3: lengths.append(word) lengths.append(len(word))
C.lengths = [word for word in words if len(word) > 3]
D.lengths = [len(word) for word in words if word > 3]
AnswerA

This list comprehension iterates over each word in words, checks if the length of the word is greater than 3, and if so includes len(word) in the new list. It correctly filters and transforms the data in a single concise expression.

Why this answer

The correct snippet must filter words with more than three characters and then transform each remaining word into its length. The list comprehension that uses len(word) in the expression and filters with len(word) > 3 accomplishes both steps correctly. Other options either compare the wrong types, return the wrong data, or incorrectly append both words and lengths.

Exam trap

The trap here is comparing a string to an integer, which is invalid, or forgetting to apply the length transformation.

63
MCQeasy

A team is reviewing code that uses if-elif-else to classify a test score. They notice that for score 90, it prints 'B' instead of 'A'. Which of the following best explains the issue?

A.The order of conditions does not matter
B.The elif condition should use >= instead of >
C.The condition for 'A' should be checked before 'B'
D.The code uses elif instead of else if
AnswerC

Python evaluates conditions top-down and stops at the first true branch. If the 'B' condition (for example score >= 80) precedes the 'A' condition, a score of 90 matches 'B' first, so ordering the 'A' check earlier fixes it.

Why this answer

In an if-elif-else chain, the first matching condition is executed and the rest are skipped. If the condition for 'A' (e.g., score >= 90) is placed after the condition for 'B' (e.g., score >= 80), a score of 90 will match the 'B' condition first and never reach the 'A' condition. To fix this, the most restrictive condition (highest grade) must be checked first.

Exam trap

Python Institute often tests the misconception that condition order is irrelevant in if-elif-else chains, tempting candidates to pick Option A, when in fact the sequential evaluation makes order crucial.

How to eliminate wrong answers

Option A is wrong because the order of conditions in an if-elif-else chain is critical; Python evaluates them sequentially and executes only the first true branch, so changing order can change the output. Option B is wrong because the issue is not about using > vs >=; even if the 'B' condition used >=, a score of 90 would still match it first if 'A' is checked later. Option D is wrong because elif is the correct Python syntax for 'else if'; using 'else if' would cause a syntax error, and the code runs without error, just with incorrect logic.

64
MCQmedium

A programmer writes code that uses a while loop to process user input until the user types 'exit'. The code currently prints 'Done' after the loop, but it never exits. What is the most likely cause?

A.The loop condition is 'while True'
B.The print statement is indented incorrectly
C.The input function is called outside the loop
D.The variable controlling the loop is not updated inside the loop
AnswerD

The loop condition depends on a variable that must change each iteration to eventually become false. If that variable is never reassigned inside the loop body, the condition stays true forever, so the loop never terminates and 'Done' is never reached.

Why this answer

If the variable controlling the loop (e.g., the user's input) is never updated inside the while loop, the loop condition will never become false, causing an infinite loop. In this scenario, the programmer likely reads input once before the loop but does not call input() again inside the loop to update the variable, so the loop never sees the 'exit' value.

Exam trap

Python Institute often tests the distinction between reading input once versus repeatedly inside a loop, and the trap here is that candidates may think 'while True' is always the cause of an infinite loop, overlooking the fact that a loop variable not being updated is the more precise and common reason.

How to eliminate wrong answers

Option A is wrong because 'while True' creates an infinite loop only if there is no break statement; the question states the loop never exits, but 'while True' with a proper break inside could still exit, so it is not the most likely cause. Option B is wrong because an incorrectly indented print statement would cause a syntax error or unexpected output, not an infinite loop that never exits. Option C is wrong because calling input() outside the loop would read a single value and never update the loop condition, which is essentially the same as D, but D more precisely states that the variable controlling the loop is not updated inside the loop, which is the root cause.

65
MCQhard

You are working on a network automation script that reads a configuration file containing firewall rules. Each rule is a dictionary with keys 'source_ip', 'dest_ip', 'action'. The script must iterate over the rules and print all rules where action is 'allow'. However, the script is not printing any output even though there are allow rules in the file. The code snippet is: rules = [{'source_ip':'10.0.0.1','dest_ip':'10.0.0.2','action':'allow'}, {'source_ip':'10.0.0.2','dest_ip':'10.0.0.3','action':'deny'}] for rule in rules: if rule('action') == 'allow': print(rule) What is the most likely cause of the problem?

A.The dictionary does not have an 'action' key
B.The developer used rule['action'] instead of rule.get('action')
C.The for loop syntax is incorrect; it should be for rule in rules:
D.The developer used rule('action') instead of rule['action']
AnswerD

Dictionaries are accessed by subscript, not by calling them as functions. Writing `rule('action')` attempts to invoke the dict as a callable, raising `TypeError: 'dict' object is not callable`, so the loop aborts before printing. Using `rule['action']` retrieves the value and satisfies the 'allow' filter.

Why this answer

In Python, dictionary values are accessed using square brackets (e.g., rule['action']) or the .get() method, not parentheses. Using parentheses like rule('action') attempts to call the dictionary as a function, which raises a TypeError and prevents the script from executing, so no output is printed even though allow rules exist.

Exam trap

The trap here is that candidates may overlook the subtle difference between parentheses and brackets for dictionary access, assuming both work similarly, but Python strictly requires square brackets for key lookup.

How to eliminate wrong answers

Option A is wrong because the dictionary clearly has an 'action' key (as shown in the provided data). Option B is wrong because using rule['action'] is actually the correct way to access a dictionary key; the problem is not about using .get() vs brackets, but about using parentheses instead of brackets. Option C is wrong because the for loop syntax 'for rule in rules:' is correct and not the cause of the issue.

66
Multi-Selecteasy

Which THREE of the following are valid list operations?

Select 3 answers
A.my_list.add(5)
B.my_list.extend([5,6])
C.my_list.push(5)
D.my_list.insert(0,5)
E.my_list.append(5)
AnswersB, D, E

extend() accepts an iterable and appends each of its elements individually to the end of the list, so [5,6] adds two separate items. This is a genuine list method that mutates the list in place, satisfying the valid-operation criterion.

Why this answer

Option B, my_list.extend([5,6]), is valid because Python lists provide the extend() method, which appends each element of the given iterable to the end of the list, so [5,6] adds two separate items. Option D, my_list.insert(0,5), is valid because insert(index, value) is a standard list method that places the value 5 at index 0, shifting existing elements to the right. Option E, my_list.append(5), is valid because append() is the canonical list method for adding a single element to the end of the list.

Option A, my_list.add(5), is not a list operation; add() belongs to set objects, not lists. Option C, my_list.push(5), is not a Python list method; push() is associated with stack-like structures in other languages (e.g., JavaScript arrays), whereas Python lists use append().

Exam trap

Python Institute often tests the distinction between list methods and methods from other data structures (like `add()` for sets or `push()` for stacks) to catch candidates who confuse Python's list API with those of other languages or collections.

67
Multi-Selectmedium

A developer is writing a function that takes a list of numbers and returns the sum of all even numbers. Which two code snippets correctly implement this function? (Select two.)

Select 2 answers
A.def sum_even(nums): return [n for n in nums if n%2==0]
B.def sum_even(nums): total=0; for i in range(len(nums)): if nums[i]%2==0: total+=nums[i]*2; return total
C.def sum_even(nums): total=0; for n in nums: if n%2==0: total+=n; return total
D.def sum_even(nums): total=0; for n in nums: if n%2==1: total+=n; return total
E.def sum_even(nums): return sum(n for n in nums if n%2==0)
AnswersC, E

Correct: loop adds evens to total.

Why this answer

It initializes a total variable to 0, iterates over each number in the list, checks if it is even using the modulo operator (n % 2 == 0), and adds the number to the total. This correctly accumulates the sum of all even numbers and returns the final total.

Exam trap

Python Institute often tests the distinction between returning a filtered list versus returning the sum of filtered values, and the trap here is that candidates may confuse list comprehensions (which produce a list) with generator expressions or accumulator logic that produce a single numeric result.

68
MCQmedium

A warehouse script stores stock quantities in the list levels = [4, 0, 7, 0, 2]. A developer wants to build a new list, in_stock, containing only the quantities greater than zero, preserving the original order. Which code correctly produces [4, 7, 2]?

A.in_stock = [levels[q] for q in levels if q > 0]
B.in_stock = [q for q in levels if q >= 0]
C.in_stock = [q if q > 0 for q in levels]
D.in_stock = [q for q in levels if q > 0]
AnswerD

This list comprehension iterates over levels in order and keeps each quantity only when q > 0, so zeros are filtered out and 4, 7, and 2 are collected in their original sequence. The result is a brand-new list, leaving levels unchanged. It is the idiomatic single-expression way to filter a list in Python.

Why this answer

A comprehension of the form [expression for item in iterable if condition] walks the list in order and includes only items satisfying the condition. Testing q > 0 excludes the zeros while keeping 4, 7, and 2 in their original positions, and it builds a separate list rather than modifying the source.

Exam trap

The trap here is confusing the comprehension's filtering if clause with a conditional expression, which would additionally require an else branch.

69
MCQhard

A developer is troubleshooting a loop that terminates earlier than expected. The code is: i = 0; while i < 5: if i == 3: break; print(i); i += 1. What is the output?

A.0 1 2 3 4
B.0 1 2 3
C.0 1
D.0 1 2
AnswerD

The loop prints i while i is below 5, but the break statement exits immediately when i equals 3, before that value is printed. Output is therefore 0, 1 and 2, terminating earlier than the expected 0 through 4.

Why this answer

The loop starts with i=0 and increments i by 1 each iteration. When i reaches 3, the break statement executes, immediately terminating the loop. Therefore, only i values 0, 1, and 2 are printed, making option D correct.

Exam trap

The trap here is that candidates often mistakenly think the break happens after printing the value that triggers it (i==3), rather than before the print statement in the same iteration.

How to eliminate wrong answers

Option A is wrong because it includes 3 and 4, but the break at i==3 stops the loop before printing 3 or incrementing to 4. Option B is wrong because it includes 3, but the break occurs before the print(i) statement for i==3, so 3 is never output. Option C is wrong because it stops at 1, but the loop continues until i==3, printing 0, 1, and 2.

70
MCQmedium

A Python developer is writing a script to process a list of order IDs. The script must skip any order ID that is an empty string and continue processing the remaining IDs. Inside a `for` loop over the list, which statement should be used to skip the current iteration when an empty string is encountered and proceed with the next order ID?

A.pass
B.continue
C.exit
D.break
AnswerB

`continue` skips the rest of the current iteration and jumps to the next item in the loop. When an empty string is detected, executing `continue` abandons processing for that order ID and moves directly to the next one, exactly matching the requirement to skip blanks while continuing through the list.

Why this answer

The `continue` statement abandons the current iteration and proceeds with the next element, which is the correct behavior for skipping empty order IDs while still processing the rest of the list. `break` would stop the loop entirely, `pass` does nothing, and `exit` would terminate the interpreter, so none of those match the filtering requirement.

Exam trap

The trap here is choosing `break` when the intent is to skip only the current item; `break` ends the whole loop, while `continue` moves to the next iteration.

71
MCQmedium

A logistics analyst maintains a list `weights` representing the mass of parcels in kilograms. The analyst needs to determine how many parcels weigh more than 10 kg, but the list also contains a few `None` values that indicate missing measurements and must not be counted. Which code correctly counts only the parcels heavier than 10 kg while ignoring missing entries?

A.count = 0 for w in weights: if w is not None and w > 10: count += 1
B.count = 0 for w in weights: if w > 10: count += 1
C.count = sum(1 for w in weights if w > 10)
D.count = 0 for w in weights: if w > 10 or w is None: count += 1
AnswerA

The condition first checks that the element is not None, short-circuiting before the numeric comparison. This prevents a TypeError on missing measurements and correctly increments the counter only for parcels whose weight exceeds 10 kg. It satisfies both requirements: counting heavy parcels and ignoring None entries, using standard Python truth evaluation.

Why this answer

The correct code uses a combined condition that first verifies the element is not None, then compares it with 10. This ordering exploits short-circuit evaluation so that None never reaches the numeric comparison. As a result, only actual numeric weights greater than 10 increment the counter, and missing measurements are silently skipped as required by the analyst.

Exam trap

The trap here is assuming that a simple numeric comparison will automatically skip None values, when in fact comparing None with an integer raises a TypeError.

72
MCQhard

A developer writes the following code snippet: for i in range(3): for j in range(2): if i == j: break else: print(i, 'outer') What is the output?

A.0 outer\n2 outer
B.2 outer
C.0 outer\n1 outer\n2 outer
D.No output
AnswerB

The inner loop breaks only when i equals j, so for i=0 and i=1 the else clause is skipped. For i=2, j never equals 2, so the inner loop completes and the else runs, printing '2 outer'.

Why this answer

The code uses nested loops with a `for-else` construct. The `else` block executes only if the inner loop completes without a `break`. When `i == j`, the `break` exits the inner loop, skipping the `else`.

For `i=0`, `j=0` triggers `break`; for `i=1`, `j=1` triggers `break`; for `i=2`, the inner loop runs `j=0,1` without any `i==j` (since 2 != 0 and 2 != 1), so the `else` executes, printing `2 outer`. Thus, only option B is correct.

Exam trap

Python Institute often tests the `for-else` behavior in nested loops, and the trap here is that candidates mistakenly think the `else` runs after every outer iteration or that `break` only exits the outer loop, when in fact `break` only exits the innermost loop and the `else` is tied to that inner loop's completion status.

How to eliminate wrong answers

Option A is wrong because it incorrectly includes `0 outer`; when `i=0`, the inner loop breaks at `j=0` (since `i==j`), so the `else` does not execute. Option C is wrong because it claims all three values print; only `i=2` avoids the break condition, so `0 outer` and `1 outer` are never printed. Option D is wrong because there is output: the `else` block prints `2 outer` when `i=2`.

73
MCQmedium

Refer to the exhibit. What is the output of the code?

A.0 1 2 4 5
B.1 2 4 5
C.1 2 3 4 5
D.2 4 5
AnswerB

Skipping 3 occurs because the loop body executes `continue` when the counter equals 3, bypassing the `print()` call for that iteration while the loop proceeds to 4 and 5. Values 1, 2, 4 and 5 are therefore printed, matching the required output exactly.

Why this answer

The code uses a for loop with range(1,6) to iterate over numbers 1 through 5. Inside the loop, an if statement checks if the current number equals 3; if true, the continue statement skips the print(i) for that iteration. Thus, when i is 3, the print is skipped, so the output is '1 2 4 5'.

Option B is correct because it matches this output.

Exam trap

Candidates often confuse range(1,6) with range(5) or miss that continue skips only the current iteration, not the whole loop. They may also forget that range start is inclusive and end is exclusive.

How to eliminate wrong answers

Option A is wrong because it includes 0, but the loop starts at 0 and prints it before the continue condition is met, so 0 should be printed; however, the correct output includes 0, so Option A is actually correct? Wait, let me re-evaluate: The loop range(5) produces 0,1,2,3,4. When i==3, continue skips print(i), so printed values are 0,1,2,4. Option A says '0 1 2 4 5' which includes 5, but range(5) stops at 4, so 5 is never generated.

Option A is wrong because it incorrectly includes 5. Option C is wrong because it includes 3, but the continue statement skips printing when i==3, so 3 should not appear. Option D is wrong because it omits 0 and 1, but the loop prints 0 and 1 before the continue condition is encountered.

74
MCQhard

A developer wants to generate a list of squares of integers from 1 to 10 inclusive. Which list comprehension is correct?

A.[x**2 for x in range(11)]
B.[x**2 for x in range(10)]
C.[x**2 for x in range(1, 10)]
D.[x**2 for x in range(1, 11)]
AnswerD

The `range(1, 11)` call yields integers 1 through 10, since the stop value is exclusive, satisfying the inclusive upper bound. Each value is squared by the `x**2` expression and collected into a new list, producing exactly the ten required squares without filtering or conditional logic.

Why this answer

`range(1, 11)` generates integers from 1 to 10 inclusive, and the list comprehension `[x**2 for x in range(1, 11)]` squares each integer, producing the desired list of squares. The `range()` function's stop value is exclusive, so `range(1, 11)` stops at 10, covering all numbers from 1 to 10.

Exam trap

Python Institute often tests the exclusive nature of the `stop` argument in `range()`, trapping candidates who forget that `range(10)` stops at 9 and `range(1, 10)` stops at 9, leading them to choose options that omit the final value (10) or include an unwanted starting value (0).

How to eliminate wrong answers

Option A is wrong because `range(11)` generates integers from 0 to 10 inclusive, including 0, which is not in the required range (1 to 10). Option B is wrong because `range(10)` generates integers from 0 to 9, missing 10 and including 0. Option C is wrong because `range(1, 10)` generates integers from 1 to 9, missing 10.

75
Multi-Selecthard

Which TWO of the following code snippets will produce the output '0 1 2'? (Choose two.)

Select 2 answers
A.for i in range(5): if i%2==0: print(i); else: continue
B.i=0; while i<3: print(i); i+=1; else: print('done')
C.for i in range(5): if i>2: break; print(i)
D.for i in range(3): print(i)
E.i=0; while i<3: print(i)
AnswersC, D

Correct: prints 0,1,2 then breaks.

Why this answer

The loop iterates over range(5) (0,1,2,3,4), but the break statement executes when i > 2, so the loop terminates after printing 0, 1, and 2. Option D is correct because range(3) generates exactly the sequence 0, 1, 2, and each value is printed in order.

Exam trap

Python Institute often tests the distinction between a for loop with range() and a while loop that requires an explicit increment; the trap here is that Option E looks like it should work but omits the increment, leading to an infinite loop, which candidates may overlook if they mentally add the missing i+=1.

Page 1 of 2 · 99 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Control Flow, Loops, Lists and Logic questions.