Courseiva

PCEP · domain

Functions, Tuples, Dictionaries and Exceptions

Practise Certified Entry-Level Python Programmer PCEP Functions, Tuples, Dictionaries and Exceptions practice questions — original exam-style scenarios with answer choices, explanations, and analysis of common mistakes.

82 questions21 easy34 medium27 hard

Focused practice

Practice Functions, Tuples, Dictionaries and Exceptions 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 Functions, Tuples, Dictionaries and Exceptions

Functions, Tuples, Dictionaries and Exceptions 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 Functions, Tuples, Dictionaries and Exceptions 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 Functions, Tuples, Dictionaries and Exceptions questions (82)

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

1

Which THREE of the following statements about Python exception handling are correct?

Medium
2

A developer writes a function to calculate the average of a list of numbers, but the function sometimes returns a wrong result when the list contains non-numeric values. What is the best way to handle this?

Easy
3

What is the output of the following code? def greet(name, greeting='Hello'): print(greeting, name) greet('Alice')

Easy
4

What is the output of the following dictionary comprehension? {x: x**2 for x in range(3)}

Medium
5

Which THREE of the following are valid dictionary methods? (Choose three.)

Medium
6

What is the output of this code?

Hard
7

Refer to the exhibit. What is the output?

Hard
8

Refer to the exhibit. What is the output?

Medium
9

A system administrator has a Python script that uses a tuple to store immutable configuration parameters, such as server address and port. A new business requirement arises: one of these parameters (the port number) must be changeable at runtime without restarting the script. The other parameters must remain immutable. The administrator wants to minimize changes to the existing codebase and maintain clarity. Which approach best satisfies the requirement while keeping the code maintainable?

Easy
10

A network configuration tool stores device settings in a dictionary where each setting key may have multiple values from different configuration sources. For example, the key 'dns_servers' might have values from the DHCP server and manual configuration. The current implementation simply assigns values: settings[key] = value. If the same key appears multiple times, only the last value is kept, losing previous values. The developer must modify the data structure so that all values for a key are preserved. The solution should be efficient for both adding new values and accessing all values for a key. Which modification is best?

Hard
11

Refer to the exhibit. What is the output?

Hard
12

Which TWO of the following are true about function arguments in Python? (Choose two.)

Medium
13

A critical automation system uses a try-except block to handle errors during file operations. The current code uses a bare except: clause to catch any error and perform cleanup. However, when an operator tries to stop the program with Ctrl+C, the KeyboardInterrupt exception is caught, and the cleanup routine runs, preventing a clean exit. Additionally, if the system runs out of memory, MemoryError is caught. The developers need to modify the exception handling so that system-exiting exceptions (such as KeyboardInterrupt and SystemExit) are not caught, but other exceptions (e.g., FileNotFoundError, PermissionError) are still handled for cleanup. Which modification best achieves this?

Hard
14

A developer is writing a robust script that must handle file reading errors. The script should catch only I/O-related exceptions (e.g., FileNotFoundError, PermissionError) and let other exceptions propagate. Which exception handling structure is best suited?

Hard
15

A function receives a dictionary that may contain nested dictionaries. The function must modify the dictionary without affecting the original passed argument. Which technique ensures a complete independent copy?

Hard
16

What is the output of the following code? def div(a, b): try: return a / b except ZeroDivisionError: raise ValueError('Invalid division') try: print(div(10, 0)) except ValueError as e: print(e) except ZeroDivisionError: print('Zero division')

Hard
17

Which of the following will raise a TypeError?

Hard
18

What happens when you try to modify a tuple? t = (1, 2, 3) t[0] = 0

Easy
19

What is the output of the code?

Easy
20

You are a developer for a financial application that processes transactions. The application uses a dictionary to store account balances where keys are account numbers (strings) and values are floats. A function `transfer(from_acc, to_acc, amount)` is supposed to subtract amount from `from_acc` and add it to `to_acc`. However, some transfers are resulting in incorrect balances: the `from_acc` balance is reduced but the `to_acc` balance is not increased. The code uses `try-except` to catch KeyError if an account does not exist. Upon inspection, the function first checks if both accounts exist, then performs subtraction, then addition, and finally returns success. No exceptions are raised during the problematic transfers. The accounts definitely exist. What is the most likely cause?

Hard
21

A developer writes a function that should return the sum of two numbers, but the code returns 0 instead. What is the most likely cause? def add(a, b): result = a + b print(add(3, 4))

Easy
22

Given a list of names = ['Alice', 'Bob', 'Charlie'], a developer wants to create a dictionary mapping each name to its length. Which expression accomplishes this?

Easy
23

A function is defined as: def min_max(nums): return min(nums), max(nums). What type of value does it return?

Medium
24

Match each Python function to its description.

Medium
25

A developer writes a function that returns multiple values as a tuple. Which of the following is a valid way to unpack the result into separate variables?

Medium
26

Which of the following correctly creates a tuple with a single element 5?

Easy
27

A developer writes a function that takes a tuple as an argument and tries to modify an element inside the tuple. What happens?

Easy
28

Which exception is raised when trying to access a dictionary key that does not exist?

Hard
29

A server logs are stored as a list of tuples: `logs = [('2024-01-10', 'INFO', 'Started'), ('2024-01-10', 'ERROR', 'Disk full')]`. A developer wants to count how many ERROR logs exist. Which code snippet correctly counts them?

Hard
30

Which of the following statements about function arguments are true? (Select all that apply)

Hard
31

A script uses a dictionary to store counts of words. The code `counts['apple'] += 1` raises a KeyError the first time because the key doesn't exist. Which approach best solves this?

Medium
32

Refer to the exhibit. What happens when this code is executed?

Hard
33

Refer to the exhibit. What is the output?

Medium
34

Based on the exhibit, where did the exception originate?

Hard
35

A function is designed to process a list and returns a modified list. The developer wants to avoid unintended side effects on the original list when it is passed as an argument. Which approach best ensures the original list remains unchanged?

Medium
36

Refer to the exhibit. What is the output?

Medium
37

Which TWO of the following statements about tuples in Python are true?

Medium
38

A script counts occurrences of words in a text file. The current code uses: if word in count_dict: count_dict[word] += 1 else: count_dict[word] = 1. Which alternative is more concise and Pythonic?

Medium
39

Refer to the exhibit. What is the output?

Medium
40

A large e-commerce platform uses a Python function to calculate the average rating from a tuple of customer ratings. The function is called thousands of times per second with the same ratings tuple (which is static across many calls). The function currently computes sum(ratings) / len(ratings) each time, causing a performance bottleneck. The development team wants to optimize the function without changing its signature (it still takes the tuple as argument). They also want to avoid using global variables or external libraries. Which approach best optimizes the function?

Medium
41

Refer to the exhibit. What is the output?

Hard
42

Refer to the exhibit. What exception is raised when this code is executed?

Easy
43

A junior developer wrote a function that calculates the average of a list of numbers. Inside the function, they used a variable named 'list' to store the input parameter. Later, they tried to call the built-in list() function to convert a string to a list inside the same function, but it raised a TypeError. The error occurs because the name 'list' now refers to the parameter, not the built-in. The function must be fixed without changing its external behavior. Which solution is the best practice?

Medium
44

Order the steps to create and use a list in Python.

Medium
45

What is the output of the following code? def f(): try: raise ValueError('error1') except ValueError: raise TypeError('error2') try: f() except TypeError as e: print(e) except ValueError: print('ValueError')

Hard
46

A Python script processes a list of tuples representing coordinates: `points = [(1,2), (3,4), (5,6)]`. The developer wants to create a dictionary mapping each coordinate to its distance from origin. Which code correctly creates the dictionary?

Hard
47

Consider the code: try: try: raise TypeError except ValueError: print('A') except TypeError: print('B') finally: print('C'). What is printed?

Hard
48

A function `def process(data):` modifies the dictionary passed as argument by adding a new key. The developer wants to avoid modifying the original dictionary. What should the function do?

Easy
49

Match each Python string method to its action.

Medium
50

A Python script uses a dictionary to store user session data. The developer writes `user = {'id': 101, 'name': 'Alice'}` and later tries to access `user['email']`. What is the outcome?

Medium
51

What is the output of the following code? def test(): try: return 1 finally: return 2 print(test())

Hard
52

A team is building a configuration parser that reads a file containing key=value pairs. They use a dictionary to store the configuration. The parser function `load_config(filename)` opens the file, reads line by line, splits on '=', and populates a dictionary. Some lines have comments starting with '#'. The developer wants to ensure that the dictionary is not polluted with comment lines. They write: `if line.startswith('#'): continue`. However, after parsing, the dictionary contains an entry with key '#' because some lines have no '=' sign. For example, a line like `#comment` is being added as a key with value None. The developer wants to fix this. Which modification should be made?

Medium
53

Order the steps to define a class and create an object in Python.

Medium
54

A function returns a tuple. Which code correctly unpacks the tuple? def min_max(numbers): return min(numbers), max(numbers) result = min_max([3, 1, 2])

Medium
55

In a try-except block, a developer has two except clauses: except ValueError: and except: (bare except). If the code in the try block raises a ValueError, which except clause is executed?

Hard
56

A programmer needs to store configuration settings keyed by string, where each key maps to a list of allowed values. Which data structure is most appropriate?

Medium
57

What is the output of the code in the exhibit?

Medium
58

A developer is using a lambda function that takes two arguments and returns their sum. Which of the following lambda expressions is correct?

Hard
59

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

Hard
60

Refer to the exhibit. What is the output when the code is executed?

Hard
61

Which TWO of the following are valid ways to create a tuple containing the elements 1 and 2? (Select two.)

Medium
62

Which TWO of the following are valid ways to create a dictionary with initial key-value pairs? (Select exactly 2)

Medium
63

A developer writes a function that appends an item to a list: def add_item(item, my_list=[]): my_list.append(item); return my_list. They call add_item(1) twice. What are the return values of the two calls?

Medium
64

Refer to the exhibit. What is the output?

Hard
65

What is the output of the code?

Medium
66

A developer wants to use a tuple to store the names of the months. They attempt to change an element: months = ("Jan","Feb","Mar"); months[1] = "Februar". What is the result?

Easy
67

Which THREE of the following are characteristics of Python tuples?

Easy
68

A support technician is running a Python script that parses a configuration file and stores key-value pairs in a dictionary called 'config'. The script then uses these values to set application parameters. The configuration file is optional, and some expected keys may be missing. Currently, the script crashes with a KeyError when accessing a missing key. The technician needs to modify the script to safely retrieve a value or return 'N/A' if a key is missing. The script must remain efficient and readable. Which modification best achieves this?

Easy
69

Which THREE of the following are valid ways to handle an exception in Python?

Hard
70

What does the following code output? try: x = int('abc') except ValueError: print('Invalid')

Easy
71

Which code sorts a list of strings by their length in descending order? lst = ['aa', 'b', 'ccc']

Medium
72

What is the result of the following expression? d = {'a': 1} d.get('b', 0)

Easy
73

Refer to the exhibit. What type of exception occurred?

Easy
74

Which TWO of the following are valid methods that can be called on a tuple object? (Choose two.)

Easy
75

Given the tuple t = (1, 2, 3, 4, 5), which expression returns the last element?

Medium
76

Refer to the exhibit. What is the output?

Hard
77

Which TWO of the following are valid ways to merge two dictionaries in Python 3.5+? (Assume dict1 = {'a':1} and dict2 = {'b':2})

Medium
78

Which TWO of the following exceptions are built-in Python exceptions? (Select exactly 2)

Easy
79

Refer to the exhibit. What is the output?

Medium
80

A dictionary student = {'name': 'John', 'age': 20}. To safely get the grade with a default of 'N/A', which code should be used?

Easy
81

A developer needs to determine the number of elements in a tuple named 't'. Which code snippet will correctly return the length?

Easy
82

Consider the following code: def foo(x, y): return x * y result = foo(y=2, 3) What is the error?

Medium

Frequently asked questions

What does the Functions, Tuples, Dictionaries and Exceptions domain cover on the PCEP exam?
Functions, Tuples, Dictionaries and Exceptions 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 82 Functions, Tuples, Dictionaries and Exceptions 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 Functions, Tuples, Dictionaries and Exceptions questions?
Yes — the session launcher on this page filters questions to this domain only. Choose any session length for inline explanations and scoring.
python-pcep PYTHON-PCEP functions data structures Practice Questions