Practice PCEP Functions, Tuples, Dictionaries and Exceptions questions with full explanations on every answer.
Start practicing
Functions, Tuples, Dictionaries and Exceptions — 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 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?
2A 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?
3A 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?
4A 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?
5A 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?
6A 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?
7A developer writes a function that takes a tuple as an argument and tries to modify an element inside the tuple. What happens?
8A 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?
9Which TWO of the following statements about tuples in Python are true?
10Which THREE of the following are valid ways to handle an exception in Python?
11What is the output of the code?
12What is the output of this code?
13You 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?
14A 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?
15Order the steps to create and use a list in Python.
16Order the steps to define a class and create an object in Python.
17Match each Python function to its description.
18Match each Python string method to its action.
19A 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))
20Which of the following correctly creates a tuple with a single element 5?
21A 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?
22Consider the following code: def foo(x, y): return x * y result = foo(y=2, 3) What is the error?
23Which exception is raised when trying to access a dictionary key that does not exist?
24A developer is using a lambda function that takes two arguments and returns their sum. Which of the following lambda expressions is correct?
25What does the following code output? try: x = int('abc') except ValueError: print('Invalid')
26Given the tuple t = (1, 2, 3, 4, 5), which expression returns the last element?
27Which of the following will raise a TypeError?
28Which TWO of the following are valid ways to create a dictionary with initial key-value pairs? (Select exactly 2)
29Which of the following statements about function arguments are true? (Select all that apply)
30Which TWO of the following exceptions are built-in Python exceptions? (Select exactly 2)
31Based on the exhibit, where did the exception originate?
32What is the output of the code in the exhibit?
33What is the output of the code?
34A 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?
35A 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?
36In 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?
37Given a list of names = ['Alice', 'Bob', 'Charlie'], a developer wants to create a dictionary mapping each name to its length. Which expression accomplishes this?
38A function is defined as: def min_max(nums): return min(nums), max(nums). What type of value does it return?
39A dictionary student = {'name': 'John', 'age': 20}. To safely get the grade with a default of 'N/A', which code should be used?
40Consider the code: try: try: raise TypeError except ValueError: print('A') except TypeError: print('B') finally: print('C'). What is printed?
41Which TWO of the following are valid methods that can be called on a tuple object? (Choose two.)
42Which TWO of the following are true about function arguments in Python? (Choose two.)
43Which THREE of the following are valid dictionary methods? (Choose three.)
44Refer to the exhibit. What exception is raised when this code is executed?
45Refer to the exhibit. What happens when this code is executed?
46Refer to the exhibit. What is the output when the code is executed?
47What is the output of the following code? def greet(name, greeting='Hello'): print(greeting, name) greet('Alice')
48A 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])
49What is the output of the following code? def test(): try: return 1 finally: return 2 print(test())
50What is the result of the following expression? d = {'a': 1} d.get('b', 0)
51Which code sorts a list of strings by their length in descending order? lst = ['aa', 'b', 'ccc']
52What 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')
53What happens when you try to modify a tuple? t = (1, 2, 3) t[0] = 0
54What is the output of the following dictionary comprehension? {x: x**2 for x in range(3)}
55What 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')
56Which TWO of the following are valid ways to create a tuple containing the elements 1 and 2? (Select two.)
57Refer to the exhibit. What type of exception occurred?
58Refer to the exhibit. What is the output?
59Refer to the exhibit. What is the output?
60A developer needs to determine the number of elements in a tuple named 't'. Which code snippet will correctly return the length?
61A 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?
62A 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?
63A 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?
64A 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?
65Which TWO of the following are valid ways to merge two dictionaries in Python 3.5+? (Assume dict1 = {'a':1} and dict2 = {'b':2})
66Which THREE of the following are characteristics of Python tuples?
67Which THREE of the following statements about Python exception handling are correct?
68A 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?
69A 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?
70A 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?
71A 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?
72A 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?
73A 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?
74Refer to the exhibit. What is the output?
75Refer to the exhibit. What is the output?
76Refer to the exhibit. What is the output?
77Refer to the exhibit. What is the output?
78Refer to the exhibit. What is the output of the code?
79Refer to the exhibit. What is the output?
80Refer to the exhibit. What is the output?
81Refer to the exhibit. What is the output?
82Refer to the exhibit. What is the output?
Deep-dive questions
The most-searched questions in this domain — detailed explanations, worked examples, full answer breakdowns.
The Functions, Tuples, Dictionaries and Exceptions 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 82 questions in the Functions, Tuples, Dictionaries and Exceptions domain, covering the 28% of the exam attributed to this domain in the official Python Institute blueprint. 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 Functions, Tuples, Dictionaries and Exceptions 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