PCEP · domain
Control Flow, Loops, Lists and Logic
This PCEP domain covers Python's control flow and core data structures: if/elif/else, while and for loops, break and continue, lists, and basic boolean logic. Questions present short code snippets or scenario tasks and ask you to predict output, choose the correct loop, or select a working list comprehension.
Focused practice
Practice Control Flow, Loops, Lists and Logic questions
Scored sessions drawing only from this domain — pick a length below.
Start 20-question practice test →What this domain covers
What to know about Control Flow, Loops, Lists and Logic
You must read short Python snippets and correctly state their output or pick code that solves a stated task. The single most important thing is tracking list contents and loop variables step by step, especially around break, continue, and range bounds.
Predicting output of for and while loops, including break, continue, and else clauses
Using list methods like append, insert, remove, sort, and slice indexing correctly
Writing and reading list comprehensions with conditions and expressions
Applying boolean operators and, or, not and comparison chains in if/elif/else logic
Watch out for
Common Control Flow, Loops, Lists and Logic exam traps
- ▸Assuming a for loop's else clause runs after break; it only runs when the loop ends without break.
- ▸Forgetting that range() excludes the stop value, causing off-by-one errors in loops and slices.
- ▸Confusing list methods that mutate in place with expressions that return a new list, like sorted() versus sort().
Question index
All Control Flow, Loops, Lists and Logic questions (99)
Click any question to see the full explanation, or start a practice session above.
What does the following code print? x = 10 if x > 5: if x > 15: print("A") else: print("B") else: print("C")
Easy2Which two of the following are valid ways to create a list with elements 1, 2, 3? (Select two.)
Easy3A logistics coordinator stores shipment weights in a list `weights = [12, 18, 7, 25]`. She needs to find the average weight of all shipments. Which code snippet correctly computes and prints the average?
Medium4A 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.)
Hard5A list of numbers is defined as nums = [1, 2, 3, 4, 5]. Which expression returns the last element?
Easy6A logistics coordinator tracks delivery statuses in a list of strings. The coordinator wants to build a new list containing only the statuses that are not equal to `"delivered"`, preserving the original order. Which code fragment produces the desired list `pending`?
Medium7A developer is writing a Python script that should keep prompting for a password until the user enters the correct one. The script must not run forever if the user never guesses correctly, so it should give up after 5 attempts. Which loop construct is most appropriate for this scenario?
Easy8A 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?
Easy9Given the code: x = [1, 2, 3] y = x y.append(4) print(x) What is the output?
Hard10A 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?
Hard11A 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?
Easy12A data analyst has a list named readings containing numeric sensor values. She needs to build a new list that contains only the values strictly greater than 10, preserving their original order. Which code fragment produces this result?
Medium13Which two of the following list methods modify the original list in place? (Choose two.)
Easy14A Python developer is writing a script that processes a list of sensor readings stored in the variable readings. The developer needs to iterate over the list and print each reading, but wants the loop to stop immediately if a reading of -999 is encountered, because that value indicates a sensor malfunction. Which code snippet correctly implements this behavior?
Medium15A student is writing a Python script to sum all even numbers in a list `nums`. The script should ignore odd numbers. Which code correctly computes the sum?
Easy16A developer needs to iterate over a list of network interfaces and print only the names that start with 'eth'. Which code should be used?
Medium17Refer to the exhibit. What does the else clause of the inner for loop do?
Hard18A programmer is writing a Python function that processes a list of integers. The function must remove all negative numbers from the list while preserving the order of the remaining elements, and it must do so in place (modifying the original list). Which two code snippets correctly achieve this? (Choose two.)
Hard19Which THREE statements about the break statement in Python are correct? (Choose three.)
Medium20A developer writes a recursive function to compute factorial, but it causes a RecursionError. Which of the following is the most likely cause?
Hard21What is the output of the code? numbers = [1, 2, 3, 4] result = [x**2 for x in numbers if x % 2 == 0] print(result)
Easy22What is the output of the following code? for i in range(1, 6): if i == 3: continue print(i, end=' ')
Easy23Which TWO of the following list operations modify the list in place?
Hard24Which TWO of the following code snippets will print the numbers 0, 1, 2, 3, 4?
Hard25A 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?
Medium26A Python programmer is reviewing a script that processes a list of order totals. The script must print each total that is greater than 100 and stop scanning entirely the first time it encounters a total of exactly 0. Which two statements about the loop logic are correct? (Choose two.)
Hard27How many times will the following loop print 'Hi'? for i in range(3): print('Hi')
Easy28A developer is auditing loop constructs in a Python script. Which TWO statements about `break`, `continue`, `else`, and `range` are correct in Python? (Choose two.)
Hard29A data analyst has a list `readings` of numeric sensor values and needs to build a new list `scaled` that contains each reading multiplied by 2, but only for readings that are positive. Negative and zero readings should be excluded. Which code correctly produces `scaled`?
Hard30A validation script defines a list named flags containing boolean values. The script must determine whether every flag is True and print 'All clear' only in that case; otherwise it should print 'Check needed'. Which code fragment implements this logic correctly?
Medium31A software tester is examining a list of error codes: `errors = [404, 500, 403, 404, 200]`. She wants to determine if the code 404 appears in the list and print 'Found' if it does, otherwise 'Not found'. Which code correctly achieves this?
Medium32A monitoring script checks a list of sensor readings and must stop examining them as soon as a reading above 100 is found, without checking any remaining readings. The readings list contains at least one value above 100. Which loop control approach implements this behavior correctly?
Hard33During a lab exercise, a student writes the following code to print a countdown from 3 down to 1, but the code enters an infinite loop and never stops. The code is: count = 3 while count > 0: print(count) Which change makes the loop terminate after printing 3, 2, and 1?
Easy34Arrange the steps to install a third-party Python package using pip.
Medium35A 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?
Medium36Which THREE of the following are valid ways to create a list with elements 10, 20, 30?
Medium37A 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?
Easy38A programmer is writing a script to process a list of sensor readings. The script should stop processing as soon as a reading of 0 is encountered. Which statement should be placed inside the loop to achieve this?
Medium39A programmer is building a simple inventory tracker using a Python list named stock that contains integer quantities. They need to add 10 to every quantity in the list, modifying the list in place. Which code correctly performs this operation?
Medium40A developer is writing a Python script to validate a list of usernames. The script must examine each username in the list and print 'Invalid' as soon as a username shorter than 3 characters is found, then stop checking the remaining usernames. Which control flow statement should be used inside the loop to terminate it immediately when the invalid username is encountered?
Easy41A developer needs to iterate over a list named `colors` and print each color on a separate line. Which code snippet correctly accomplishes this?
Easy42A developer is building a simple inventory check. The list stock holds integers representing item quantities. He wants to append the string 'low' to a separate list alerts once for each quantity that is less than 5. Which code correctly populates alerts?
Hard43A developer writes a while loop to count down from 10 to 1 and then stop. Which condition should be used?
Easy44A game developer writes a loop to process a list of player scores: `scores = [45, 82, 67, 91]`. She wants to print only the scores that are greater than 80. Which loop correctly accomplishes this?
Easy45A developer is writing a Python script that must iterate over the characters of the string stored in variable `word` and print each character on its own line, without using index numbers. Which of the following loops accomplishes this?
Easy46A programmer is reviewing code that uses loops and conditional statements. Which TWO of the following statements about Python control flow are correct? (Choose two.)
Medium47A programmer wants to create a list of even numbers from 0 to 10 inclusive. Which list comprehension is correct?
Easy48Which TWO of the following are true about Python's if statement?
Hard49Which list method modifies the list in place by adding all elements of another iterable to the end?
Medium50A developer needs to check if all elements in a list of integers are even. Which code correctly implements this?
Hard51Which code correctly creates a list of squares for numbers 1 to 5 using a list comprehension?
Easy52A data analyst maintains `matrix = [[1, 2], [3, 4], [5, 6]]` and wants a flat list `flat` containing every number in row order, that is `[1, 2, 3, 4, 5, 6]`. Which code produces this result?
Hard53A programmer has a list of tuples representing (product, price) and wants to find the highest price. Which code correctly finds the maximum price?
Hard54What is the output of the following code? numbers = [1, 2, 3, 4, 5] total = 0 for i in numbers: if i % 2 == 0: continue total += i print(total)
Hard55A Python developer is writing a program that prompts the user to enter a positive integer. The program should repeatedly ask for input until the user enters a number greater than zero. Which loop construct is most appropriate to implement this requirement?
Easy56Which of the following best describes the behavior of the 'range' function in a for loop?
Medium57Which two of the following statements about Python lists are true?
Medium58A teacher writes a program that must print each student name from a list called roster on its own line, but stop printing entirely as soon as the name "STOP" is encountered, without printing "STOP" itself. Which loop body achieves this?
Medium59A 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?
Hard60A Python developer is writing a function that takes a list of numbers and returns a new list containing only the numbers that are divisible by 3 or 5. The developer writes the following code: def filter_numbers(nums): result = [] for n in nums: if n % 3 == 0 or n % 5 == 0: result.append(n) return result Which statement about this function is true?
Hard61A quality-control engineer stores defect codes in a list `codes` and wants to print each code until a sentinel value `'STOP'` is encountered, at which point the loop should end without printing `'STOP'`. Which loop correctly achieves this behavior?
Medium62A Python programmer is working with a list of strings called words. The programmer wants to create a new list that contains the lengths of each word, but only for words that have more than three characters. Which code snippet correctly produces this list?
Medium63A 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?
Easy64A 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?
Medium65You 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?
Hard66Which THREE of the following are valid list operations?
Easy67A 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.)
Medium68A warehouse script stores stock quantities in the list levels = [4, 0, 7, 0, 2]. A developer wants to build a new list, in_stock, containing only the quantities greater than zero, preserving the original order. Which code correctly produces [4, 7, 2]?
Medium69A 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?
Hard70A Python developer is writing a script to process a list of order IDs. The script must skip any order ID that is an empty string and continue processing the remaining IDs. Inside a `for` loop over the list, which statement should be used to skip the current iteration when an empty string is encountered and proceed with the next order ID?
Medium71A logistics analyst maintains a list `weights` representing the mass of parcels in kilograms. The analyst needs to determine how many parcels weigh more than 10 kg, but the list also contains a few `None` values that indicate missing measurements and must not be counted. Which code correctly counts only the parcels heavier than 10 kg while ignoring missing entries?
Medium72A 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?
Hard73Refer to the exhibit. What is the output of the code?
Medium74A developer wants to generate a list of squares of integers from 1 to 10 inclusive. Which list comprehension is correct?
Hard75Which TWO of the following code snippets will produce the output '0 1 2'? (Choose two.)
Hard76A 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?
Easy77A Python programmer is analyzing a list of integers named numbers. The programmer wants to create a new list that contains only the even numbers from numbers, each multiplied by 10. Which two of the following code snippets correctly produce the desired list? (Choose two.)
Hard78A 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?
Medium79A Python developer is building a quiz application. The program stores correct answers in a list named `key` and user responses in a list named `answers`. The developer wants to count how many positions match between the two lists, stopping the comparison as soon as the first mismatch is found so that a diagnostic message can be shown. Which control-flow statement should be used inside the loop to stop iterating immediately when a mismatch occurs?
Medium80A Python developer is validating a list of sensor readings stored in `readings`. The developer needs to build a new list containing only readings that are strictly greater than 10. Which two code fragments correctly produce a list of only the values greater than 10? (Choose two.)
Medium81A developer is writing a Python inventory reconciliation script. They need to examine each element of a list named `stock` and, for every element, execute a block of code that updates a running total. They do not want the loop to terminate early under any condition. Which statement should be placed at the beginning of the loop body to iterate over every element in order?
Easy82A logistics analyst is writing a Python script that processes a list of shipment weights in kilograms. The analyst needs to display each weight one at a time and also know its position in the list, starting from 1 rather than 0. Which approach most directly accomplishes this?
Easy83A 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?
Medium84A 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?
Hard85A student is writing a program that stores the daily steps walked over a week in a list. She wants to determine whether any day had fewer than 1000 steps, and if so, report the first such day's index. Which approach correctly finds the index of the first value below 1000?
Medium86A developer is debugging a script that uses a `while` loop to process items from a queue. The loop is intended to run until the queue is empty, but the script hangs indefinitely. Which of the following is the most likely cause?
Hard87A 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)
Medium88A developer is reviewing loop constructs that iterate over the list scores = [10, 20, 30]. Which two statements about iterating this list are true? (Choose two.)
Medium89A 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?
Hard90A ticket system stores seat rows in the list rows = [[1, 2], [3, 4], [5, 6]]. A developer needs to print every individual seat number on its own line, in order, from 1 through 6. Which code accomplishes this?
Medium91A Python developer is writing a script that processes a list of temperatures in a loop. Inside the loop, a conditional block handles sub-zero readings by appending a warning to a report. The developer notices that the loop body is executing even for temperatures that are not sub-zero. Which statement about Python's `if`/`elif`/`else` structure explains why a block guarded by `if temp < 0:` should not execute for a temperature of 5?
Hard92A 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?
Medium93An inventory script stores product quantities in a list named stock. The script must print the running total of quantities from the start of the list up to, but not including, the first zero quantity it encounters. Which code fragment produces this behavior?
Easy94A developer needs to implement a loop that prints numbers from 10 down to 1. Which loop correctly achieves this?
Medium95Which loop is more efficient for iterating over a large list when you only need the values, not indices?
Easy96A developer is writing a Python script to process a list of integers representing inventory counts. The developer needs to iterate over the list and, for each element, perform an action, but also needs to be able to terminate the entire loop early when a sentinel value (0) is encountered. Which two statements about loop control in Python are correct? (Choose two.)
Hard97Arrange the steps to handle an exception in Python using try-except.
Medium98A quality engineer tracks defect counts per shift in a list called defects. She needs the running total of all defects after every shift, producing a list of cumulative sums with the same length as defects. Which approach produces that cumulative list?
Medium99Which three of the following statements about lists are true? (Choose three.)
HardOther domains
All PCEP exam domains
Frequently asked questions
- What does the Control Flow, Loops, Lists and Logic domain cover on the PCEP exam?
- You must read short Python snippets and correctly state their output or pick code that solves a stated task. The single most important thing is tracking list contents and loop variables step by step, especially around break, continue, and range bounds.
- How many questions are in this domain?
- This page lists all 99 Control Flow, Loops, Lists and Logic questions in the PCEP question bank. The actual exam draws from this domain proportionally to its weighting in the official exam blueprint.
- What is the best way to practise this domain?
- Start with a short focused session (10 questions) to identify gaps, then work through explanations. Repeat with a longer session once the weak areas feel solid.
- Can I practise only Control Flow, Loops, Lists and Logic questions?
- Yes — the session launcher on this page filters questions to this domain only. Choose any session length for inline explanations and scoring.