Courseiva

PCEP · domain

Control Flow, Loops, Lists and Logic

Practise Certified Entry-Level Python Programmer PCEP Control Flow, Loops, Lists and Logic practice questions — original exam-style scenarios with answer choices, explanations, and analysis of common mistakes.

89 questions26 easy33 medium30 hard

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

Control Flow, Loops, Lists and Logic questions test whether you can apply the concept in context, not just recognise a definition.

How the topic appears in realistic exam-style scenarios.

Which detail in the question changes the correct answer.

How to eliminate plausible but wrong options.

How to connect the question back to the wider exam objective.

Watch out for

Common Control Flow, Loops, Lists and Logic exam traps

  • Answering from memory before reading the full scenario.
  • Missing a constraint such as cost, availability, security, scope or command context.
  • Choosing a broad answer when the question asks for the most specific fix.
  • Ignoring why the wrong options are tempting.

Question index

All Control Flow, Loops, Lists and Logic questions (89)

Click any question to see the full explanation, or start a practice session above.

1

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

Easy
2

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

Easy
3

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

Hard
4

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

Easy
5

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?

Medium
6

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?

Medium
7

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?

Easy
8

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?

Easy
9

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

Hard
10

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?

Hard
11

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?

Easy
12

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?

Medium
13

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

Easy
14

What is the output of the code?

Medium
15

What is the output of the code?

Easy
16

Refer to the exhibit. What is the output?

Medium
17

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

Hard
18

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?

Hard
19

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?

Medium
20

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

Hard
21

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

Medium
22

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

Hard
23

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

Medium
24

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

Hard
25

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

Hard
26

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?

Medium
27

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)

Easy
28

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

Easy
29

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

Hard
30

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

Hard
31

What is the output of the code?

Medium
32

Refer to the exhibit. What is the output?

Easy
33

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

Hard
34

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?

Medium
35

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

Easy
36

Refer to the exhibit. What is the output?

Easy
37

Match each exception type to its description.

Medium
38

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?

Easy
39

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

Medium
40

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?

Medium
41

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

Medium
42

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

Hard
43

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?

Easy
44

Refer to the exhibit. What is printed?

Easy
45

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

Medium
46

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

Easy
47

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

Hard
48

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

Easy
49

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

Medium
50

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

Hard
51

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

Easy
52

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

Hard
53

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

Hard
54

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

Medium
55

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

Medium
56

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?

Hard
57

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?

Easy
58

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?

Medium
59

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?

Hard
60

Which THREE of the following are valid list operations?

Easy
61

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

Medium
62

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

Easy
63

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

Medium
64

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

Hard
65

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?

Hard
66

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

Medium
67

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

Hard
68

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

Hard
69

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

Hard
70

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?

Easy
71

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?

Medium
72

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?

Medium
73

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?

Hard
74

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?

Hard
75

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)

Medium
76

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?

Hard
77

What is the output of the code?

Hard
78

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?

Hard
79

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

Easy
80

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

Easy
81

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

Medium
82

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?

Medium
83

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?

Medium
84

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

Medium
85

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

Easy
86

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

Medium
87

Match each Python concept to its description.

Medium
88

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

Medium
89

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

Hard

Frequently asked questions

What does the Control Flow, Loops, Lists and Logic domain cover on the PCEP exam?
Control Flow, Loops, Lists and Logic questions test whether you can apply the concept in context, not just recognise a definition.
How many questions are in this domain?
This page lists all 89 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.
Certified Entry-Level Python Programmer PCEP Control Flow, Loops, Lists and Logic Practice Questions