CCNA Control Flow Loops Questions

13 of 88 questions · Page 2/2 · Control Flow Loops topic · Answers revealed

76
MCQhard

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

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

Correct: get with fallback handles both key casings.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

77
MCQeasy

Which code correctly and efficiently sums only positive numbers from a list?

A.for num in numbers: if num > 0: total += num else: break
B.for num in numbers: if num <= 0: pass else: total += num
C.for num in numbers: if num > 0: total += num else: continue
D.for num in numbers: if num <= 0: continue total += num
AnswerD

Correct and efficient; skips non-positive.

Why this answer

Option D is correct because it uses `continue` to skip non-positive numbers and then unconditionally adds the remaining numbers to `total`. This is both efficient (no unnecessary `else` branch) and correct: it sums only positive numbers without breaking the loop prematurely or adding zero/negative values.

Exam trap

Python Institute often tests the distinction between `break` and `continue`, and the trap here is that candidates mistakenly use `break` (thinking it skips one item) or add unnecessary `else` branches, when `continue` is the correct way to skip an iteration without terminating the loop.

How to eliminate wrong answers

Option A is wrong because it uses `break` when a non-positive number is encountered, which stops the loop entirely; this fails if a negative number appears before the end of the list, causing later positive numbers to be skipped. Option B is wrong because it uses `pass` for non-positive numbers, which does nothing but still requires an `else` clause; while it works, it is less efficient and less idiomatic than the correct approach. Option C is wrong because it uses `continue` inside an `else` block after adding positive numbers, which is redundant and confusing; the `else` block is unnecessary because the loop would naturally continue to the next iteration anyway.

78
MCQeasy

A programmer needs to iterate over a list of strings and print each string in uppercase. Which loop correctly accomplishes this?

A.for i, item in enumerate(mylist): print(item.upper())
B.for item in mylist: item = item.upper()
C.for item in mylist: print(item.upper)
D.for i in range(len(mylist)): print(mylist[i].upper())
AnswerA, D

Also correct, but the question expects exactly one correct; both A and C are correct. I'll adjust: make only A correct? No, both are valid. I need to change distractors so that only one is correct. Let's replace A with a wrong one.

Why this answer

Option A is correct because it uses a for loop with enumerate to iterate over the list, and calls the string method upper() (with parentheses) to convert each item to uppercase before printing. This ensures each string is properly transformed and output.

Exam trap

Python Institute often tests the distinction between referencing a method (without parentheses) and calling it (with parentheses), leading candidates to pick Option C when they forget that methods must be invoked to execute.

How to eliminate wrong answers

Option B is wrong because it assigns the uppercase string to the loop variable item, but this does not modify the original list or print anything; the assignment has no visible effect. Option C is wrong because it prints the method object item.upper instead of calling it with parentheses, so it outputs a string representation of the bound method, not the uppercase string.

79
MCQmedium

A developer writes: result = [x**2 for x in range(10) if x % 2 == 0]. What does this code produce?

A.A list of even numbers squared
B.A generator object
C.A list of squares of all numbers from 0 to 9
D.A list containing [0, 4, 16, 36, 64]
AnswerD

Correct: squares of even numbers 0,2,4,6,8.

Why this answer

The code uses a list comprehension with a conditional filter: `[x**2 for x in range(10) if x % 2 == 0]`. It iterates over numbers 0 through 9, keeps only even numbers (those where `x % 2 == 0`), squares each, and collects the results into a list. The resulting list is `[0, 4, 16, 36, 64]`, which are the squares of the even numbers 0, 2, 4, 6, and 8.

Exam trap

The trap here is that candidates may overlook the `if` filter and think the comprehension squares all numbers 0–9, or they may confuse list comprehensions with generator expressions, which use parentheses instead of square brackets.

How to eliminate wrong answers

Option A is wrong because it describes the result as 'a list of even numbers squared,' which is ambiguous and could be interpreted as the even numbers themselves being squared (which is true), but the phrasing is imprecise and the option does not list the actual values; the correct answer is the specific list. Option B is wrong because list comprehensions in Python produce a list object, not a generator object; a generator would require parentheses instead of square brackets (e.g., `(x**2 for x in range(10) if x % 2 == 0)`). Option C is wrong because it claims the list contains squares of all numbers from 0 to 9, but the `if x % 2 == 0` filter excludes odd numbers, so only even numbers are squared.

80
Multi-Selectmedium

Which two of the following expressions evaluate to True? (Choose two.)

Select 2 answers
A.(10 > 5) and (5 < 3)
B.not (0 or 1)
C.3 in [1,2,3] and 4 not in [1,2,3]
D.'a' in 'abc' or 5 > 10
E.(True and False) or (False or True)
AnswersC, E

Both conditions true.

Why this answer

Option C is correct because the expression `3 in [1,2,3]` evaluates to `True` (since 3 is an element of the list), and `4 not in [1,2,3]` also evaluates to `True` (since 4 is not present). The `and` operator requires both operands to be `True`, and here both are, so the entire expression is `True`.

Exam trap

Python Institute often tests the combination of membership operators (`in`, `not in`) with logical operators (`and`, `or`), and the trap here is that candidates may mis-evaluate option D as `False` because they focus on the `5 > 10` part, forgetting that `or` only needs one `True` operand, making the whole expression `True` — but the question expects only C and E as the two correct answers, so D is a distractor that is actually True but not selected.

81
MCQmedium

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

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

Unsorted timestamps lead to inaccurate gap detection. Sorting before loop fixes it.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

82
MCQmedium

A data analyst has a list of temperature readings in Celsius and wants to create a new list containing only readings that are valid (>= -273.15 and <= 1000). Which code correctly creates the filtered list?

A.valid = [temp for temp in temps if -273.15 <= temp <= 1000]
B.valid = [temp for temp in temps if temp > -273.15 and temp < 1000]
C.valid = [] for t in temps: if t > -273.15 and t < 1000: valid.append(t)
D.valid = list(filter(lambda t: t >= -273.15, temps))
AnswerA

Correct; uses chained comparison to include boundaries.

Why this answer

Option A is correct because it uses a list comprehension with a chained comparison (`-273.15 <= temp <= 1000`) that correctly includes both boundary values. This syntax is Pythonic and ensures temperatures equal to -273.15 or 1000 are considered valid, matching the requirement exactly.

Exam trap

Python Institute often tests the distinction between inclusive (`<=`, `>=`) and exclusive (`<`, `>`) comparisons, and the trap here is that candidates may overlook the boundary values or choose a syntactically incorrect loop structure like Option C.

How to eliminate wrong answers

Option B is wrong because it uses strict inequalities (`>` and `<`) instead of `>=` and `<=`, which excludes the boundary values -273.15 and 1000, failing the requirement. Option C is wrong because it uses invalid Python syntax: the list initialization and `for` loop are not separated by a newline or semicolon, and the indentation is missing, making it a syntax error. Option D is wrong because it only filters for `t >= -273.15` but does not enforce the upper bound of `<= 1000`, so temperatures above 1000 would be incorrectly included.

83
MCQmedium

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

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

Correct; step -1 from 10 down to 1.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

84
MCQeasy

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

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

Direct iteration over values is most efficient.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

85
Drag & Dropmedium

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

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

Steps
Order

Why this order

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

86
Matchingmedium

Match each Python concept to its description.

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

Concepts
Matches

A name that references a value in memory

A block of reusable code that performs a specific task

A file containing Python definitions and statements

A collection of modules organized in directories

A blueprint for creating objects

Why these pairings

These are key concepts in Python programming that help organize code.

87
MCQmedium

A program needs to print the index and value of each item in a list named 'items'. Which code snippet correctly does this?

A.for i, item in enumerate(items): print(i, item)
B.Both A and B are correct
C.for i in range(len(items)): print(i, items[i])
D.for item in items: print(items.index(item), item)
AnswerB

Both snippets correctly print index and value.

Why this answer

Option B is correct because both `for i, item in enumerate(items): print(i, item)` and `for i in range(len(items)): print(i, items[i])` correctly iterate over the list while printing the index and value. `enumerate()` is the Pythonic way, but `range(len())` is also valid and commonly used in PCEP-level questions.

Exam trap

Python Institute often tests the misconception that `items.index(item)` is a reliable way to get the current index, but it fails with duplicate values and is computationally expensive, leading candidates to incorrectly select option D.

How to eliminate wrong answers

Option A is wrong because it is actually correct, but the question states 'Both A and B are correct' as the answer, so A alone is not the full correct choice. Option C is wrong because it is also correct, but again not the full answer. Option D is wrong because `items.index(item)` returns the first occurrence of the value, which will produce incorrect indices if the list contains duplicate values; it is also inefficient and not the intended way to access both index and value.

88
Multi-Selecthard

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

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

Indexing starts at 0.

Why this answer

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

Exam trap

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

← PreviousPage 2 of 2 · 88 questions total

Ready to test yourself?

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