Practice PCEP Control Flow, Loops, Lists and Logic questions with full explanations on every answer.
Start practicing
Control Flow, Loops, Lists and Logic — choose a session length
Free · No account required
Click any question to see the full explanation and answer options, or start a focused practice session above.
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?
2A programmer needs to iterate over a list of strings and print each string in uppercase. Which loop correctly accomplishes this?
3A 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?
4A list of numbers is defined as nums = [1, 2, 3, 4, 5]. Which expression returns the last element?
5A 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?
6A 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?
7A programmer needs to check if at least one element in a list of booleans flags is True. Which expression correctly does this?
8Given the code: x = [1, 2, 3] y = x y.append(4) print(x) What is the output?
9A programmer wants to create a list of even numbers from 0 to 10 inclusive. Which list comprehension is correct?
10What is the output of the code?
11A 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?
12Which TWO of the following are valid ways to create a list with elements 10, 20, 30?
13Which TWO of the following code snippets will print the numbers 0, 1, 2, 3, 4?
14Which THREE of the following are valid list operations?
15You 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?
16You 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?
17Arrange the steps to handle an exception in Python using try-except.
18Arrange the steps to install a third-party Python package using pip.
19Match each exception type to its description.
20Match each Python concept to its description.
21A 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?
22A 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?
23A 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.)
24Which code correctly and efficiently sums only positive numbers from a list?
25A developer needs to iterate over a list of network interfaces and print only the names that start with 'eth'. Which code should be used?
26A programmer has a list of tuples representing (product, price) and wants to find the highest price. Which code correctly finds the maximum price?
27Which code correctly creates a list of squares for numbers 1 to 5 using a list comprehension?
28A developer needs to implement a loop that prints numbers from 10 down to 1. Which loop correctly achieves this?
29A 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.)
30Which two of the following list methods modify the original list in place? (Choose two.)
31Which two of the following expressions evaluate to True? (Choose two.)
32Which three of the following statements about lists are true? (Choose three.)
33Refer to the exhibit. What is the output?
34Refer to the exhibit. What is printed?
35Refer to the exhibit. What is the output?
36A 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?
37A developer writes a while loop to count down from 10 to 1 and then stop. Which condition should be used?
38A 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?
39A 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?
40A 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?
41A developer writes: result = [x**2 for x in range(10) if x % 2 == 0]. What does this code produce?
42A 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?
43A 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?
44A developer writes a recursive function to compute factorial, but it causes a RecursionError. Which of the following is the most likely cause?
45Which TWO of the following are valid ways to iterate over a list in reverse order? (Choose two.)
46Which THREE statements about the break statement in Python are correct? (Choose three.)
47Which TWO of the following code snippets will produce the output '0 1 2'? (Choose two.)
48What is the output of the code?
49What is the output of the code?
50What is the output of the code?
51Refer to the exhibit. What is the output?
52Refer to the exhibit. What is printed?
53Refer to the exhibit. What is the output?
54How many times will the following loop print 'Hi'? for i in range(3): print('Hi')
55Which loop is more efficient for iterating over a large list when you only need the values, not indices?
56A company stores employee data as a list of dictionaries. Each dictionary has keys 'name' and 'age'. Which code correctly counts employees older than 30?
57A 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?
58A 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?
59Which list method modifies the list in place by adding all elements of another iterable to the end?
60A 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)
61A developer wants to generate a list of squares of integers from 1 to 10 inclusive. Which list comprehension is correct?
62A developer needs to check if all elements in a list of integers are even. Which code correctly implements this?
63Which TWO of the following list operations modify the list in place?
64Which THREE of the following are valid ways to iterate over a list?
65Which TWO of the following are true about Python's if statement?
66A 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?
67A 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?
68A 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?
69A program needs to print the index and value of each item in a list named 'items'. Which code snippet correctly does this?
70What is the output of the code? numbers = [1, 2, 3, 4] result = [x**2 for x in numbers if x % 2 == 0] print(result)
71A 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?
72Which of the following best describes the behavior of the 'range' function in a for loop?
73What does the following code print? x = 10 if x > 5: if x > 15: print("A") else: print("B") else: print("C")
74A 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.)
75Which two of the following are valid ways to create a list with elements 1, 2, 3? (Select two.)
76A 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.)
77A 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?
78A 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?
79A 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?
80A 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?
81Which two of the following statements about Python lists are true?
82A 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?
83A 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?
84Refer to the exhibit. What is the final value of x after executing the code?
85Refer to the exhibit. Why does the code successfully remove all even numbers but the output is [1, 3, 5]?
86Refer to the exhibit. What does the else clause of the inner for loop do?
87Refer to the exhibit. What is the output of the code?
88Refer to the exhibit. What is the final value of my_list?
The Control Flow, Loops, Lists and Logic domain covers the key concepts tested in this area of the PCEP exam blueprint published by Python Institute. Courseiva provides free domain-focused practice, mock exams, missed-question review, and readiness tracking across all PCEP domains — no account required.
The Courseiva PCEP question bank contains 88 questions in the Control Flow, Loops, Lists and Logic domain. Click any question to see the full explanation and answer breakdown.
Start with a 10-question focused session to identify your baseline accuracy in this domain. Read every explanation — even for questions you answer correctly — to understand the reasoning. Once you score consistently above 80%, move to a 20–30 question session to confirm depth before moving to the next domain.
Yes — the session launcher on this page draws questions exclusively from the Control Flow, Loops, Lists and Logic domain. Choose 10, 20, 30, or 50 questions for a focused session, or click individual questions to review them one by one.
Save your results, see per-domain analytics, and get readiness scores — free, for every certification.
Sign Up FreeFree forever · Every certification included