CCNA Control Flow, Loops, Lists and Logic Questions

75 of 88 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

Correct output.

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

Option A is correct because `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
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

Option D correctly 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.

4
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

Correct negative indexing.

Why this answer

Option B is correct because 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.

5
MCQmedium

A list contains strings and numbers: items = ['apple', 10, 'banana', 20]. A programmer wants to create a new list that contains only the strings. Which approach is correct?

A.[item for item in items if item.isdigit()]
B.[item for item in items if type(item) is 'str']
C.[item for item in items if type(item) == str]
D.[item for item in items if isinstance(item, str)]
AnswerC, D

Correct, though isinstance is preferred.

Why this answer

Option C is correct because `type(item) == str` directly compares the type of each item to the `str` type object, which returns `True` for strings and `False` for numbers. This is a valid and explicit way to filter the list comprehension to only include string elements.

Exam trap

Python Institute often tests the distinction between comparing a type object to a string literal (e.g., `type(item) is 'str'`) versus comparing to the actual type object (e.g., `type(item) == str`), trapping candidates who mistakenly think `'str'` is the same as `str`.

How to eliminate wrong answers

Option A is wrong because `isdigit()` is a string method that checks if a string consists only of digits; it would raise an `AttributeError` when called on an integer (e.g., 10) since integers do not have an `isdigit()` method. Option B is wrong because `type(item) is 'str'` compares the type object to a string literal `'str'`, which will always be `False` since `type(item)` returns a type object (e.g., `<class 'str'>`), not a string.

6
MCQmedium

A company stores employee data as a list of dictionaries. Each dictionary has keys 'name' and 'age'. Which code correctly counts employees older than 30?

A.count = 0 for i in range(len(employees)): if employees[i]['age'] <= 30: count += 1
B.count = 0 i = 0 while i < len(employees): if employees[i]['age'] > 30: count += 1
C.count = 0 for emp in employees: if emp['age'] > 30: count += 1
D.count = [emp for emp in employees if emp['age'] > 30]
AnswerC

Correctly increments count for each employee over 30.

Why this answer

Option C is correct because it uses a simple `for` loop to iterate directly over each dictionary in the `employees` list, checks if the value of the `'age'` key is greater than 30, and increments the counter accordingly. This is the most Pythonic and readable approach for counting elements that satisfy a condition.

Exam trap

Python Institute often tests the distinction between creating a filtered list and counting elements, so the trap here is that option D looks correct but produces a list instead of a numeric count, which is a subtle but critical difference.

How to eliminate wrong answers

Option A is wrong because it counts employees whose age is <= 30 (the condition is reversed) and uses an index-based loop, which is unnecessarily complex. Option B is wrong because it never initializes `count` to 0 (it would raise a `NameError` or use an undefined variable) and also uses a while loop with manual indexing, which is error-prone. Option D is wrong because it creates a list of dictionaries for employees older than 30, not a count; to get the count, you would need to wrap it in `len()`.

7
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

Adds the number value instead of 1, giving the correct sum.

Why this answer

Option B is correct because 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.

8
MCQeasy

A developer writes a loop to sum numbers from 1 to 10. The code outputs 55, but the expected sum is 55. However, the loop uses a range that includes 0. Which range should be used to achieve the correct sum?

A.range(0,11)
B.range(1,11)
C.range(0,101)
D.range(1,10)
AnswerB

Correctly generates 1..10

Why this answer

Option B (range(1,11)) is correct because range(start, stop) generates numbers from start inclusive to stop exclusive. To sum numbers 1 through 10, the range must start at 1 and end at 11 (so 10 is included). The loop that used range(0,11) included 0, but since adding 0 does not change the sum, the output was still 55 — however, the question asks for the range that achieves the correct sum without including unnecessary values.

Exam trap

Python Institute often tests the exclusive nature of range()'s stop parameter, tricking candidates into thinking range(1,10) includes 10 or that range(0,11) is equivalent to range(1,11) when the sum is unchanged by zero.

How to eliminate wrong answers

Option A is wrong because range(0,11) includes 0, which is unnecessary and could cause issues if the sum were expected to exclude zero (though here it didn't affect the result). Option C is wrong because range(0,101) would sum numbers 0 through 100, producing 5050, not 55. Option D is wrong because range(1,10) generates numbers 1 through 9, missing 10, so the sum would be 45, not 55.

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

Correct due to aliasing.

Why this answer

Option C is correct because 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

Option D is correct because 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

Catches ValueError and allows reprompt.

Why this answer

Option C is correct because 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 programmer needs to check if at least one element in a list of booleans flags is True. Which expression correctly does this?

A.True in flags
B.all(flags)
C.flags.any()
D.any(flags)
AnswerA, D

Also correct but less Pythonic; however both A and C are correct. I need to make only one correct. Replace C with a wrong option.

Why this answer

Option A is correct because the `in` operator checks membership in a list; `True in flags` returns `True` if at least one element in the list `flags` is the boolean `True`. Option D is also correct because the built-in `any()` function returns `True` if any element in the iterable is truthy, which for a list of booleans means at least one `True`.

Exam trap

Python Institute often tests the distinction between `any()` and `all()` functions, and the trap here is that candidates may confuse `any()` with a list method (like `.any()` in NumPy) or incorrectly think `all()` checks for at least one `True`.

How to eliminate wrong answers

Option B is wrong because `all(flags)` returns `True` only if every element in the list is truthy (i.e., all are `True`), not if at least one is `True`. Option C is wrong because `flags.any()` is not a valid method for Python lists; the `any()` function is a built-in, not a list method, so this would raise an `AttributeError`.

13
MCQmedium

You are writing a script to parse a log file. Each line in the log contains a timestamp and a message separated by a colon. You need to extract only the messages that contain the word 'ERROR'. The script uses a list comprehension to filter lines. However, the script crashes with a 'ValueError: not enough values to unpack' when processing some lines. The code is: lines = ['2024-01-01 12:00:00: INFO: all good', '2024-01-01 12:01:00: ERROR: something wrong'] errors = [msg for timestamp, msg in line.split(': ') for line in lines if 'ERROR' in msg] What is the correct fix?

A.Rewrite as: [line for line in lines if 'ERROR' in line]
B.Change the list to a dictionary
C.Swap the order of the for clauses to: [msg for line in lines for timestamp, msg in line.split(': ') if 'ERROR' in msg]
D.Rewrite as: [msg for line in lines if 'ERROR' in line for msg in [line.split(': ')[1]]]
AnswerD

Correct nested comprehension.

Why this answer

Option D is correct because it properly separates the filtering and unpacking steps. The original code attempts to unpack each line into timestamp and msg using `line.split(': ')`, but some lines may not contain exactly two parts after splitting (e.g., if the colon is missing or there are extra colons), causing a ValueError. Option D first filters lines containing 'ERROR', then safely extracts the message part by splitting and taking index [1] inside a nested comprehension, avoiding the unpacking error.

Exam trap

Python Institute often tests the order of `for` clauses in nested list comprehensions and the assumption that `split()` always returns a fixed number of parts, leading candidates to choose Option C which only reorders loops without fixing the unpacking error.

How to eliminate wrong answers

Option A is wrong because it returns the entire line as a string, not just the message part after the colon, so it does not meet the requirement of extracting only the messages. Option B is wrong because converting the list to a dictionary does not solve the unpacking issue; the original code would still crash on lines that cannot be split into exactly two parts. Option C is wrong because swapping the for clauses does not fix the fundamental problem: `line.split(': ')` still returns a list that may not have exactly two elements, and unpacking it into timestamp, msg will raise a ValueError if the split result has a different length.

14
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

Sorts the list in place.

Why this answer

A is correct because the `sort()` method sorts the list in place, meaning it modifies the original list object without creating a new one. D is correct because `append()` adds an element to the end of the list, directly mutating 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.

15
MCQmedium

What is the output of the code?

A.No output
B.0 1 2 3 4
C.0 1 2 4
D.0 1 2 4 5
AnswerC

Correct: 3 is skipped.

Why this answer

The code uses a for loop with range(5) to iterate over numbers 0 through 4. Inside the loop, an if statement checks if the current number equals 3; if true, the break statement exits the loop immediately. Therefore, when i becomes 3, the loop terminates before printing 3, so the output is '0 1 2' (each on a new line due to print(i) default behavior).

Option C correctly lists the printed values as 0, 1, 2, and then 4 is not printed because the loop breaks before reaching 4.

Exam trap

Python Institute often tests the interaction between break and loop iteration order, where candidates mistakenly think break skips only the current iteration (like continue) or that the loop continues after the break condition is met.

How to eliminate wrong answers

Option A is wrong because the loop does produce output: it prints 0, 1, and 2 before the break occurs. Option B is wrong because it includes 3 and 4, but the break at i == 3 prevents printing 3 and any subsequent numbers. Option D is wrong because it includes 5, but the range(5) generates numbers 0-4, so 5 is never reached, and the break also stops before 4 is printed.

16
MCQeasy

What is the output of the code?

A.1 2
B.1 2 3 Done
C.1 2 Done
D.1 2 3
AnswerA

Correct: prints 1, then 2, then loop ends.

Why this answer

The code uses a `for` loop with `range(1, 4)` which generates the sequence 1, 2, 3. Inside the loop, `if i == 3: break` causes the loop to terminate when `i` equals 3, so the loop only prints 1 and 2 before breaking. After the loop, `print('Done')` is executed because it is outside the loop, so the output is 1, 2, and Done on separate lines.

Exam trap

Python Institute often tests the distinction between `break` and `continue`, and the trap here is that candidates forget that `break` exits the loop entirely, not just the current iteration, leading them to incorrectly include the value that triggered the break in the output.

How to eliminate wrong answers

Option A is wrong because it omits 'Done' and shows only 1 and 2, but the code prints 'Done' after the loop. Option B is wrong because it prints 3 before 'Done', but the `break` statement prevents 3 from being printed. Option D is wrong because it prints 1, 2, 3 without 'Done', but the code includes `print('Done')` after the loop.

17
MCQmedium

Refer to the exhibit. What is the output?

A.5
B.2
C.9
D.1
AnswerD

After bubble sort, the smallest element is at index 0.

Why this answer

The correct answer is D (1) because the code uses a for loop to iterate over the list [1, 2, 3, 4, 5] and breaks out of the loop when the current element equals 3. The variable 'x' is assigned the value of the last element processed before the break, which is 2, but the print statement is outside the loop and prints the final value of 'x' after the loop ends, which is 2. However, the code snippet in the exhibit likely has a different logic: if the loop iterates and breaks at 3, then 'x' is 2, but the output is 1 because the loop starts at 1 and the break condition is met immediately, so 'x' remains 1.

The correct output is 1.

Exam trap

The trap here is that candidates often assume the loop variable holds the value that triggered the break, but it actually holds the value from the previous iteration, leading to off-by-one errors in output prediction.

How to eliminate wrong answers

Option A (5) is wrong because it assumes the loop completes all iterations without breaking, but the break statement exits the loop when the condition is met, so the last value of 'x' is not 5. Option B (2) is wrong because it assumes the loop processes up to the element before the break, but the break occurs at the first element (1) if the condition is 'x == 1', so 'x' is never updated to 2. Option C (9) is wrong because it is not a value present in the list or derived from the loop logic; it likely results from a misunderstanding of the loop range or break behavior.

18
MCQhard

A developer is implementing a toggle switch feature. The variable flag starts as False. Which code snippet correctly toggles the flag and performs an action based on the new value each time the code is run? (Assume action1 is performed when flag is True, action2 when False.)

A.flag = not flag; if flag: action1() else: action2()
B.if not flag: flag = True; action1() else: flag = False; action2()
C.if flag: flag = False; action1() else: flag = True; action2()
D.flag = not flag; if flag: action2() else: action1()
AnswerA

Correctly toggles then uses new value.

Why this answer

Option A is correct because it first toggles the flag using `flag = not flag`, which flips the boolean value from False to True (or vice versa). Then it uses a conditional `if flag:` to check the new value and calls `action1()` when True or `action2()` when False, exactly matching the requirement to act on the new state each time the code runs.

Exam trap

Python Institute often tests the order of operations in toggle-and-check patterns, where candidates mistakenly perform the action based on the old flag value instead of the new one after toggling.

How to eliminate wrong answers

Option B is wrong because it checks `if not flag:` first, then sets `flag = True` and calls `action1()` — but when `flag` is False, it toggles to True and runs `action1()` (correct for True), but the `else` branch sets `flag = False` and calls `action2()` — this logic is inverted: it runs `action1()` when the new flag is True but the structure is confusing and the else branch incorrectly sets flag to False when it was already True, failing to toggle properly. Option C is wrong because it checks `if flag:` first, then sets `flag = False` and calls `action1()` — this runs `action1()` when the new flag is False (since it just set it to False), which is the opposite of the requirement (action1 should run when flag is True). Option D is wrong because it correctly toggles the flag with `flag = not flag`, but then checks `if flag:` and calls `action2()` instead of `action1()`, swapping the actions — so when flag becomes True, it incorrectly runs `action2()`.

19
MCQhard

A team observes that the following code prints 'Found' even when the item is not in the list. Code: for item in mylist: if item == target: print('Found'); break; else: print('Not found'). Which modification ensures it correctly prints 'Not found' only if the item is not present?

A.Move else inside the if block
B.Replace break with continue
C.Use a flag variable to track found status
D.Align the else with the for statement (for-else construct)
AnswerD

Correct: for-else executes else only if no break occurred.

Why this answer

Option D is correct because the original code uses a for-else construct where the else block executes after the loop completes normally (i.e., without a break). However, the code has a syntax error: the else is incorrectly indented as part of the if statement, causing it to execute on every iteration when the condition is false. Aligning the else with the for statement (for-else construct) ensures the else block runs only if the loop finishes without hitting a break, which occurs when the item is not found.

Exam trap

Python Institute often tests the for-else construct by presenting code where the else is incorrectly indented under the if, leading candidates to think the else belongs to the if statement, when in fact the intended behavior requires the else to be aligned with the for.

How to eliminate wrong answers

Option A is wrong because moving the else inside the if block would cause it to execute only when item == target is true, printing 'Not found' incorrectly when the item is found, and never printing it when the item is not present. Option B is wrong because replacing break with continue would prevent the loop from exiting upon finding the item, causing the else block (if properly aligned) to never execute and the loop to continue iterating, potentially printing 'Found' multiple times and never printing 'Not found'. Option C is wrong because while using a flag variable could work, it is not the modification described in the question; the question asks which modification ensures correct behavior, and the for-else construct is the direct, Pythonic fix that avoids unnecessary extra variables.

20
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

Correct; startswith checks prefix.

Why this answer

Option C is correct because 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.

21
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 executes when the loop finishes normally (no break). Here, it appends the row if no even item was found.

22
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

Option B is correct because 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.

23
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

Correct: without base case, recursion never terminates, exceeding max recursion depth.

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.

24
Multi-Selecthard

A developer is debugging a function that uses a while loop to reverse a list in place. The current code causes an infinite loop. Which three modifications would likely fix the infinite loop? (Select three.)

Select 3 answers
A.Ensure the end index is decremented each iteration
B.Add a break statement after the swap
C.Use a temporary variable for the swap
D.Ensure the start index is incremented each iteration
E.Use a for loop instead
AnswersA, D, E

Necessary to eventually meet start condition.

Why this answer

Option A is correct because in a while loop that reverses a list in place, the end index must be decremented each iteration to move the end pointer toward the center. Without decrementing the end index, the loop condition (e.g., start < end) may never become false, causing an infinite loop. This ensures the two pointers converge and the loop terminates.

Exam trap

Python Institute often tests the misconception that adding a break or using a temporary variable alone can fix an infinite loop, when the root cause is missing index updates that prevent the loop condition from becoming false.

25
MCQmedium

A developer needs to write a loop that prints all even numbers from a list. They attempt: for num in numbers: if num % 2 == 0: print(num). However, they want a more efficient approach using list comprehension. Which alternative achieves the same result?

A.print([num for num in numbers if num % 2 == 0])
B.for num in numbers: print(num if num % 2 == 0 else None)
C.for even in [num for num in numbers if num % 2 == 0]: print(even)
D.print([num % 2 == 0 for num in numbers])
AnswerC

Correct: list comprehension filters even numbers, then loop prints each.

Why this answer

Option C is correct because it uses a list comprehension to generate a list of even numbers, then iterates over that list with a for loop, printing each even number. This achieves the same result as the original loop but with the efficiency of list comprehension for filtering, while still printing each number individually.

Exam trap

Python Institute often tests the distinction between generating a list of filtered values versus printing them individually, and the trap here is that candidates may think option A is correct because it uses list comprehension, but they overlook that it prints the entire list as a single output, not each element separately.

How to eliminate wrong answers

Option A is wrong because it prints the entire list of even numbers as a single list object, not each number individually. Option B is wrong because it prints None for every odd number (due to the else clause), altering the output. Option D is wrong because it prints a list of boolean values (True/False) indicating whether each number is even, not the even numbers themselves.

26
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

Correct squares of even numbers.

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.

27
MCQeasy

Refer to the exhibit. What is the output?

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

Correct; print is skipped for 3.

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.

28
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

Sorts the list in place.

Why this answer

Option A is correct because `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.

29
MCQmedium

What is the output of the code?

A.['Positive', 'Zero']
B.[Positive, Zero, Negative]
C.('Positive', 'Zero', 'Negative')
D.['Positive', 'Zero', 'Negative']
AnswerD

Correct: as explained.

Why this answer

The code creates a list `result` and appends strings based on the value of `x`. Since `x = 0`, the condition `x > 0` is false, so 'Positive' is not appended. The `elif x == 0` is true, so 'Zero' is appended.

The `else` block is skipped because the `elif` was executed. The final list is `['Zero']`, but the correct answer D is `['Positive', 'Zero', 'Negative']` — this suggests the actual code in the question (not shown here) iterates over multiple values or uses a loop that appends all three. The core reasoning is that list append operations accumulate elements in order, and the output is a list containing all three strings.

Exam trap

Python Institute often tests the distinction between list literals (square brackets) and tuple literals (parentheses), and the requirement for string literals to be quoted — candidates may forget quotes or confuse list/tuple syntax.

How to eliminate wrong answers

Option A is wrong because it suggests only 'Positive' and 'Zero' are in the list, but the code (as implied by the correct answer) includes 'Negative' as well. Option B is wrong because it uses bare words without quotes, which would cause a NameError in Python (undefined variables), not a list of strings. Option C is wrong because it shows a tuple with parentheses, but the code uses square brackets for a list, so the output is a list, not a tuple.

30
MCQeasy

Refer to the exhibit. What is the output?

A.[2, 5, 7, 9, 5]
B.[2, 4, 6, 8, 10]
C.[1, 4, 3, 8, 5]
D.[1, 2, 3, 4, 5]
AnswerC

Correctly doubles even-indexed values.

Why this answer

The code iterates over the list `[1, 2, 3, 4, 5]` and for each element, if it is odd, it multiplies it by 2; if it is even, it adds 2. The results are appended to a new list, producing `[1*2, 2+2, 3*2, 4+2, 5*2]` which equals `[2, 4, 6, 8, 10]`. However, the exhibit shows a different code: it modifies the original list in-place using a for loop and index, and the output is `[1, 4, 3, 8, 5]` because the condition `if x % 2 == 0` (even) triggers `x + 2`, and `else` (odd) triggers `x * 2`, applied to each element sequentially.

Exam trap

Python Institute often tests the distinction between modifying a list in-place versus creating a new list, and the trap here is that candidates misread the condition (even vs odd) or assume the output is a new list, leading them to choose the list comprehension result instead of the actual in-place modification output.

How to eliminate wrong answers

Option A is wrong because it suggests the output is `[2, 5, 7, 9, 5]`, which would require a mix of operations not present in the code (e.g., adding 3 to some elements). Option B is wrong because it assumes the code creates a new list with all elements transformed, but the actual code modifies the original list in-place and the condition checks for even numbers (not odd). Option D is wrong because it implies no transformation occurs, but the code explicitly changes each element based on the condition.

31
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

Prints 0..4.

Why this answer

Option A is correct because `range(0,5)` generates the sequence 0, 1, 2, 3, 4. The `range()` function with two arguments (start, stop) produces numbers from start inclusive up to, but not including, stop. Therefore, iterating with `for i in range(0,5): print(i)` prints exactly 0 through 4.

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.

32
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

This ensures index 0 is processed.

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.

33
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

Correct number 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.

34
MCQeasy

Refer to the exhibit. What is the output?

A.[1, 2, 3]
B.[0, 1, 2]
C.[1, 2]
D.[2, 3]
AnswerC

Correct slice.

Why this answer

The code iterates over the list [1, 2, 3] using a for loop. The variable `i` takes each element in order. The loop appends `i` to the new list `result` only if `i` is not equal to 3.

Since 3 is the last element, it is skipped, so `result` becomes [1, 2]. The final print outputs [1, 2].

Exam trap

Python Institute often tests the distinction between iterating over list elements versus list indices, and the trap here is that candidates mistakenly think the loop variable represents an index (0, 1, 2) rather than the actual list values.

How to eliminate wrong answers

Option A is wrong because it includes 3, but the condition `if i != 3` explicitly excludes 3 from being appended. Option B is wrong because it suggests the loop starts at 0, but the list contains 1, 2, 3, not indices. Option D is wrong because it omits 1 and includes 3, but the loop appends 1 and 2, and skips 3.

35
Matchingmedium

Match each exception type to its description.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Raised when a function receives an argument of correct type but inappropriate value

Raised when an operation is applied to an object of inappropriate type

Raised when a sequence subscript is out of range

Raised when a mapping key is not found in a dictionary

Raised when division or modulo operation is performed with zero as divisor

Why these pairings

These are built-in exceptions in Python that indicate specific error conditions.

36
MCQeasy

A junior developer needs to write code that processes a list of student scores and stops processing when a score of 100 is encountered, as that score represents a perfect score that should be treated separately. Which loop construct is most appropriate?

A.for score in scores: if score == 100: pass ...
B.for score in scores: if score == 100: break ... further processing
C.for i in range(len(scores)): if scores[i] == 100: exit() ...
D.while scores: score = scores.pop(); if score == 100: continue ...
AnswerB

Correct; break stops the loop.

Why this answer

Option B is correct because the `break` statement immediately exits the loop when a score of 100 is encountered, which matches the requirement to stop processing further scores. The `for` loop iterates over the list naturally, and the `if` condition checks for the perfect score, making this the most straightforward and efficient construct for this scenario.

Exam trap

Python Institute often tests the distinction between `break`, `continue`, and `pass` in loops, and the trap here is that candidates may confuse `continue` (which skips only the current iteration) with `break` (which exits the loop entirely), leading them to choose option D incorrectly.

How to eliminate wrong answers

Option A is wrong because `pass` is a no-op statement that does nothing; it would skip the 100 but continue processing subsequent scores, failing to stop the loop. Option C is wrong because `exit()` terminates the entire program, not just the loop, which is overly drastic and not appropriate for simply stopping score processing. Option D is wrong because `continue` skips the current iteration and moves to the next, but it does not stop the loop; also, using `pop()` modifies the list destructively, which is not required and can lead to unintended side effects.

37
Drag & Dropmedium

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

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

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

38
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

Correct: continue skips the current iteration for negative amounts.

Why this answer

Option D is correct because 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.

39
Multi-Selectmedium

Which TWO 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

Valid list comprehension.

Why this answer

Option A is correct because it uses a list comprehension that iterates over the tuple (10, 20, 30) and creates a new list with the same elements. This is a valid Python syntax for constructing a list from an iterable.

Exam trap

Python Institute often tests the distinction between the list() constructor requiring a single iterable argument versus multiple positional arguments, and the use of correct list literal syntax (commas vs. semicolons), to catch candidates who confuse Python with other languages like JavaScript or C.

40
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

Correct: the 'in' operator is concise and readable.

Why this answer

Option D is 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.

41
MCQeasy

Refer to the exhibit. What is printed?

A.None (error)
B.A
C.B
D.C
AnswerB

First condition met.

Why this answer

The code uses a `for` loop to iterate over the list `['A', 'B', 'C']`. The `break` statement inside the loop executes when the variable `letter` equals `'A'`, immediately terminating the loop. Therefore, only `'A'` is printed before the loop ends, making option B correct.

Exam trap

Python Institute often tests the misconception that `break` only exits the current iteration or that the loop continues after the break, leading candidates to think multiple values are printed.

How to eliminate wrong answers

Option A is wrong because the code does not produce an error; the `break` statement is syntactically valid and the loop runs without exception. Option C is wrong because `'B'` is never printed; the loop breaks before reaching the second iteration where `letter` would be `'B'`. Option D is wrong because `'C'` is never printed; the loop terminates at the first iteration before `'C'` is ever assigned to `letter`.

42
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

Correct: runs while counter is positive; stops when counter becomes 0.

Why this answer

Option D is correct because 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.

43
MCQhard

Refer to the exhibit. What is the final value of x after executing the code?

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

The loop pops the last element and inserts it at position i, but because the list is modified in-place and the length remains the same, the net effect is that the list is unchanged.

44
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

Correct condition for even.

Why this answer

Option A is correct because 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.

45
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

if statements can have multiple elif blocks (B) and the condition can be any expression that evaluates to a boolean or truthy/falsy (E).

46
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

Expands the list with elements from an iterable.

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.

47
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

Option C is correct because 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.

48
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

Correct; range(1,6) gives 1-5 and ** is exponent.

Why this answer

Option C is correct because 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.

49
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

Option B correctly 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.

50
MCQhard

Refer to the exhibit. What is printed?

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

Correct; index 2 is 9.

Why this answer

The code iterates over the list `[1, 2, 3, 4, 5]` and uses `if i % 2 == 0` to check if each number is even. When `i` is even (2 and 4), the `continue` statement skips the rest of the loop body for that iteration, so those numbers are not added to `total`. Only odd numbers (1, 3, 5) are added, resulting in `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.

51
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

Correct: stop is not included.

Why this answer

Option A is correct because 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.

52
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

Option B is correct because 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.

53
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

deepcopy creates independent copies of all nested objects.

Why this answer

Option B is correct because `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.

54
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

Correct: to print 'A' for scores >= 90, that condition must come first.

Why this answer

Option C is correct because 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.

55
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

Classic infinite loop cause.

Why this answer

Option D is correct because 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.

56
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

Dictionary access uses square brackets or get method.

Why this answer

Option D is correct because 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.

57
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

Valid method.

Why this answer

Option B is correct because the `extend()` method appends each element of the iterable (here, the list `[5,6]`) to the end of the original list, modifying it in place. This is a valid list operation in Python that adds multiple elements at once.

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.

58
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

Option C is correct because 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.

59
Multi-Selecteasy

Which TWO of the following are valid ways to iterate over a list in reverse order? (Choose two.)

Select 2 answers
A.for item in reversed(lst):
B.for i in range(len(lst)-1, -1, -1):
C.for i in range(len(lst)):
D.for item in lst[-1::-1]:
E.for item in lst:
AnswersA, B

Correct: returns an iterator that yields items in reverse.

Why this answer

Option A is correct because `reversed(lst)` returns an iterator that yields elements of the list in reverse order without modifying the original list, and the `for` loop consumes each element in that reversed sequence. Option B is correct because `range(len(lst)-1, -1, -1)` generates indices starting from the last index down to 0 (inclusive), allowing direct index-based access to list elements in reverse order.

Exam trap

Python Institute often tests the distinction between creating a reversed copy (via slicing) and iterating in reverse order (via `reversed()` or a descending range), leading candidates to mistakenly select the slice syntax as a valid iteration method when the exam expects only the two canonical loop constructs.

60
MCQmedium

Refer to the exhibit. What is the final value of my_list?

A.[1, 2, 3, 4, 5]
B.[1, 4, 9, 16, 25]
C.[1, 8, 27, 64, 125]
D.[1, 4, 27, 16, 125]
AnswerD

Even numbers (2,4) are squared, odd numbers (1,3,5) are cubed.

61
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

Correct: i increments to 3, break exits loop, so only 0,1,2 printed.

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.

62
MCQhard

Refer to the exhibit. Why does the code successfully remove all even numbers but the output is [1, 3, 5]?

A.Because the condition checks for even numbers and removes them correctly without side effects.
B.Because removing elements while iterating forward causes skipping of elements, but in this case the even numbers are at indices 0,2,4 and the removal shifts subsequent elements; however, the loop variable i increments and skips the next odd number, leading to correct removal by chance.
C.Because the range is computed once and the list is shortened, so the loop ends early.
D.Because the remove() method removes only the first occurrence, and the loop iterates backwards.
AnswerB

The code works because the even numbers are at even indices and after removal, the next element becomes at the same index, but since i increments, it skips the next element; however, the skipped elements are odd and remain, so the result is all odds.

63
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

Only when i=2 does the inner loop complete without break.

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`.

64
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

The loop increments x from 0 to 5; when x becomes 3, continue skips the print, so 3 is not printed.

65
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

Correctly generates squares for 1 through 10.

Why this answer

Option D is correct because `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.

66
Multi-Selecthard

Which THREE of the following are valid ways to iterate over a list?

Select 3 answers
A.for i in mylist:
B.i = 0 while i < len(mylist): print(mylist[i]) i += 1
C.foreach i in mylist:
D.iter(mylist)
E.for i in range(len(mylist)):
AnswersA, B, E

Direct iteration over elements.

Why this answer

Option A is correct because Python's `for i in mylist:` syntax directly iterates over each element of the list `mylist`, assigning the element value to the loop variable `i` in each iteration. This is the standard and most Pythonic way to traverse a list.

Exam trap

Python Institute often tests the distinction between creating an iterator with `iter()` and actually iterating over it, leading candidates to mistakenly think `iter(mylist)` alone is a loop construct.

67
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

Option C is correct because 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.

68
MCQeasy

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

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

Correct keyword to exit a loop.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

69
MCQmedium

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

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

85 satisfies the second if-elif.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

70
MCQmedium

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

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

Correct list comprehension with expression and filter.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

71
MCQhard

A developer runs main.py and gets True. They then modify config.py by adding `allowed_ports.append(22)` and run main.py again without restarting the interpreter. What is the output?

A.False
B.None
C.Error
D.True
AnswerD

The module is not reloaded, so the function still uses the original list.

Why this answer

Option D is correct because Python imports modules only once per interpreter session; subsequent imports use the cached module object. Since `config.py` was already imported, modifying the file does not affect the already-loaded list object in memory. The `allowed_ports` list remains unchanged, so the condition that originally returned `True` still holds.

Exam trap

The trap here is that candidates assume Python re-executes the imported module each time it is imported, but in reality, Python caches modules and only loads them once per interpreter session, so modifications to the source file after the first import are ignored.

How to eliminate wrong answers

Option A is wrong because the list was not re-imported, so the modification to `config.py` has no effect; the output remains `True`, not `False`. Option B is wrong because the code does not produce `None`; it prints the boolean result of a condition that evaluates to `True`. Option C is wrong because no error occurs; Python silently uses the cached module, and appending to a list is a valid operation that does not raise an exception.

72
MCQhard

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

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

Updating the condition variable prevents infinite loops.

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

73
MCQmedium

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

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

This would allow processing all numbers, not stopping at -1.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

74
MCQhard

A network administrator uses a Python script to analyze firewall logs. The script reads a CSV file with columns 'src_ip', 'dst_ip', 'action', 'time'. It needs to build a list of source IPs that have been blocked more than 3 times. The current code: blocked_count = {} blocked_ips = [] for row in logs: if row['action'] == 'block': if row['src_ip'] in blocked_count: blocked_count[row['src_ip']] += 1 else: blocked_count[row['src_ip']] = 1 for ip, count in blocked_count.items(): if count > 3: blocked_ips.append(ip) The script runs correctly but slowly on large logs. The administrator wants to optimize it. Which change would most improve performance?

A.Use a list comprehension for the second loop
B.Pre-allocate the blocked_ips list
C.Use a set for blocked_ips to avoid duplicates
D.Use a counter from collections module
AnswerD

Counter is optimized for frequency counting.

Why this answer

Option D is correct because using `collections.Counter` replaces the manual dictionary increment logic with a single optimized C-level operation, reducing Python bytecode execution overhead. The Counter's `most_common()` method or direct iteration over items still requires a second loop, but the first loop's increment is significantly faster due to internal C implementation, which is the primary bottleneck in large log processing.

Exam trap

The trap here is that candidates focus on the second loop's syntax (list comprehension) or data structure (set) instead of recognizing that the first loop's manual counting logic is the real performance bottleneck, which `Counter` optimizes via C-level internals.

How to eliminate wrong answers

Option A is wrong because converting the second loop to a list comprehension only marginally reduces overhead (avoids `.append()` calls) but does not address the main performance bottleneck—the first loop's manual dictionary increment. Option B is wrong because pre-allocating the list (e.g., `blocked_ips = [None] * n`) is not feasible here since the number of blocked IPs is unknown until after counting, and Python lists already handle dynamic resizing efficiently. Option C is wrong because using a set for `blocked_ips` would prevent duplicates but does not improve the counting loop's performance; the current code already ensures uniqueness by appending only once per IP due to the `count > 3` condition.

75
MCQhard

What is the output of the code?

A.Alice Check
B.Alice
C.Alice Too young
D.Alice Bob
AnswerA

Correct: Alice prints because age>=26; Bob prints 'Check' from else.

Why this answer

The code uses a for loop to iterate over a list of names. For each name, it checks if the length of the name is less than 5. 'Alice' has length 5, so the condition is false and the loop continues to the next iteration without printing anything. 'Bob' has length 3, which is less than 5, so 'Bob' is printed. After the loop, the code prints 'Check'.

Therefore, the output is 'Bob' followed by 'Check' on separate lines. Option A is correct because it matches this output.

Exam trap

Python Institute often tests the understanding that a loop's body may not execute for all elements, and that code after the loop always runs, leading candidates to incorrectly include or exclude the final print statement.

How to eliminate wrong answers

Option B is wrong because it only shows 'Alice' and misses the 'Check' output. Option C is wrong because it includes 'Too young' which is not in the code. Option D is wrong because it shows 'Alice' and 'Bob' but omits the 'Check' output.

Page 1 of 2 · 88 questions totalNext →

Ready to test yourself?

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