Be able to read short Python snippets and state the exact result or exception. The key skill is knowing that tuples cannot be changed after creation and that argument order rules make foo(y=2, 3) a SyntaxError.
Start practicing
Functions, Tuples, Dictionaries and Exceptions — choose a session length
Free · No account required
Domain overview
This domain covers defining and calling functions, positional and keyword arguments, tuple immutability and indexing, dictionary operations, and handling built-in exceptions with try/except. PCEP questions present short code snippets and ask you to predict output, identify the exact error raised, or select correct syntax from options.
Exam objectives
Defining functions with def, return values, and default or keyword parameters
Tuple creation, indexing, slicing, len(), and immutable element assignment
Dictionary creation, key access, methods like keys(), values(), and get()
Built-in exceptions such as TypeError, ValueError, KeyError, and IndexError
Assuming tuples support item assignment; modifying t[0] raises TypeError because tuples are immutable
Mixing positional and keyword arguments incorrectly, such as foo(y=2, 3), which raises SyntaxError
Confusing KeyError from a missing dictionary key with IndexError from an out-of-range sequence index
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 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?
4A developer writes a function that takes a tuple as an argument and tries to modify an element inside the tuple. What happens?
5Which TWO of the following statements about tuples in Python are true?
6Order the steps to create and use a list in Python.
7Order the steps to define a class and create an object in Python.
8Which of the following correctly creates a tuple with a single element 5?
9A 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?
10Consider the following code: def foo(x, y): return x * y result = foo(y=2, 3) What is the error?
11Which exception is raised when trying to access a dictionary key that does not exist?
12A developer is using a lambda function that takes two arguments and returns their sum. Which of the following lambda expressions is correct?
13What does the following code output? try: x = int('abc') except ValueError: print('Invalid')
14Given the tuple t = (1, 2, 3, 4, 5), which expression returns the last element?
15Which of the following will raise a TypeError?
16Which TWO of the following are valid ways to create a dictionary with initial key-value pairs? (Select exactly 2)
17Which of the following statements about function arguments are true? (Select all that apply)
18Which TWO of the following exceptions are built-in Python exceptions? (Select exactly 2)
19A 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?
20A 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?
21In 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?
22Given a list of names = ['Alice', 'Bob', 'Charlie'], a developer wants to create a dictionary mapping each name to its length. Which expression accomplishes this?
23A function is defined as: def min_max(nums): return min(nums), max(nums). What type of value does it return?
24A function is defined as: def func(*args, **kwargs): print(args, kwargs). It is called as func(1, 2, a=3, b=4). What is printed?
25A dictionary student = {'name': 'John', 'age': 20}. To safely get the grade with a default of 'N/A', which code should be used?
26A developer wants to raise a ValueError with a custom message when a negative number is passed. Which code is correct?
27Consider the code: try: try: raise TypeError except ValueError: print('A') except TypeError: print('B') finally: print('C'). What is printed?
28Which TWO of the following are valid methods that can be called on a tuple object? (Choose two.)
29Which TWO of the following are true about function arguments in Python? (Choose two.)
30Which THREE of the following are valid dictionary methods? (Choose three.)
31Refer to the exhibit. What is the output when the code is executed?
32What is the output of the following code? def greet(name, greeting='Hello'): print(greeting, name) greet('Alice')
33What is the output of the following code? def test(): try: return 1 finally: return 2 print(test())
34What is the result of the following expression? d = {'a': 1} d.get('b', 0)
35What 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')
36What happens when you try to modify a tuple? t = (1, 2, 3) t[0] = 0
37What is the output of the following dictionary comprehension? {x: x**2 for x in range(3)}
38What 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')
39Which THREE of the following are built-in exceptions in Python? (Select three.)
40Which TWO of the following are valid dictionary methods? (Select two.)
41A developer needs to determine the number of elements in a tuple named 't'. Which code snippet will correctly return the length?
42A 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?
43A developer wants to create a tuple containing a single integer value 5. Which code snippet correctly creates such a tuple?
44A 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?
45Which THREE of the following statements about Python exception handling are correct?
46A 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?
47A 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?
48A 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?
49A developer is writing a Python function that must accept any number of positional arguments and return their sum. The function should also work when called with zero arguments. Which function definition correctly achieves this?
50A developer needs to store configuration settings as key-value pairs and later retrieve the value for a key that may not exist, providing a default value if the key is missing. Which dictionary method should be used?
51A developer writes a function to safely divide two numbers and wants to explicitly raise a ValueError when the divisor is zero, rather than letting a ZeroDivisionError propagate. The function signature is `def safe_divide(a, b):`. Which code snippet correctly accomplishes this?
52A developer writes a function that assigns a new value to an element of a list passed as an argument. After the function returns, the caller observes that the original list has been modified. The developer wants a second function that appends an item to a list but leaves the caller's list unchanged. Which definition achieves this?
53A developer defines a function `def add_item(item, basket=[]):` and calls it multiple times without providing a basket argument. After three calls with different items, what is the content of the default basket?
54A developer writes a function that needs to accept any number of positional arguments and return their sum. Which function definition correctly collects all positional arguments into a tuple named values?
55A developer defines a function with the signature def configure(host, port=8080, protocol='http'). A call is made as configure('web01', protocol='https'). Which statement describes what happens?
56A developer is writing a function that should accept any number of positional arguments and return their sum. Which function definition correctly achieves this?
57A logistics team stores shipment data as `shipment = {'id': 'A17', 'weight_kg': 12.5, 'destination': 'Osaka'}`. A developer needs to retrieve the destination but wants the program to keep running and supply the string 'UNKNOWN' if the key is ever missing from a shipment record. Which statement should the developer use?
58A developer defines a tuple `config = ('localhost', 8080, True)`. Later, the code attempts `config[1] = 9090`. What happens when this line executes?
59A developer needs to count how many times each word appears in a list named words. The code starts with counts = {} and then iterates over the list. Which loop body correctly increments the count for each word, creating the key when it is first seen?
60A developer wants to create a tuple that contains a single element, the integer 5. Which of the following expressions produces exactly that?
61A developer is working with a dictionary `config = {'host': 'localhost', 'port': 8080}`. They need to perform operations that modify or access the dictionary without causing errors. Which two of the following operations are valid and will not raise an exception? (Choose two.)
62A developer writes a function `def log_event(message, level='INFO'):` that appends a formatted string to a list. The developer calls `log_event('disk full')` and then `log_event('retrying', level='WARN')`. What is the result of these two calls?
63A developer is writing a function that accepts a dictionary of student names and their scores. The function should return the name of the student with the highest score. If the dictionary is empty, it should return `None`. Which code snippet correctly implements this?
64A developer writes a function to log sensor readings. The function is defined as: def log_reading(sensor_id, value, unit="C"): return f"{sensor_id}: {value}{unit}" The developer calls log_reading("T1", 22, unit="F"). What is the result?
65A function is defined to accept a variable number of positional arguments and return their sum. The code is: def total(*args): return sum(args) What is the result of `total(1, 2, 3)`?
66An inventory script defines `def add_stock(item, quantity, *restock_dates):` and is called as `add_stock('bolt', 40, '2024-01-05', '2024-02-11')`. Inside the function, the developer wants to count how many restock dates were supplied. Which expression correctly reports that count?
67A developer writes a function to update a configuration dictionary: def update_config(config, key, value): config[key] = value; return config. They call it as: my_config = {'debug': False}; result = update_config(my_config, 'debug', True). What is the value of my_config after the call, and why?
68A programmer needs to store a fixed set of error codes that should not change during program execution. Which data type is most appropriate for this purpose?
69A developer writes a function to calculate the area of a rectangle: def area(length, width): return length * width. They call it as area(5, 3). What is the result and why?
70A developer writes a function that retrieves a value from a dictionary and handles missing keys: def get_value(data, key): try: return data[key] except KeyError: return None What happens if data is not a dictionary but a list, and key is an integer index?
71A developer uses a tuple to store immutable configuration data: config = ('localhost', 8080, True). They then write: host, port, secure = config. What is the result of this statement?
72A developer wants to create a dictionary that maps employee IDs to their department names. The IDs are integers, and departments are strings. Which of the following correctly creates such a dictionary?
73A developer writes a function that reads an integer from a string and adds it to a running total. The code uses try: total += int(value) followed by except ValueError: total += 0. During testing, a value of '12.5' is supplied. What is the resulting behaviour?
74A developer writes a function that attempts to access a dictionary key that may not exist: def get_value(data, key): try: return data[key] except KeyError: return None. They call it as get_value({'a': 1}, 'b'). What is the result and why?
75A payroll script calls `calculate_bonus(employee_id, base)` inside a try block. The function raises a custom exception `BonusError` when the employee is not eligible, and the script wants to log that specific failure while still letting an unexpected ZeroDivisionError propagate to a global handler. Which except clause should the developer write?
76A developer is writing a function that accepts a variable number of arguments and needs to handle them as a tuple. Which two of the following statements about tuples and function arguments are true? (Choose two.)
77A Python developer is writing a function that takes a tuple of numbers and returns a new tuple containing only the even numbers. They write the following code: def filter_even(numbers): result = () for num in numbers: if num % 2 == 0: result += (num,) return result What is the primary reason this function works correctly?
78A developer writes a function `def process(data):` that uses a try-except-else-finally block. The try block reads from a file, the except block handles IOError, the else block processes the data, and the finally block closes the file. If no exception occurs, which blocks execute and in what order?
79A programmer is writing a function that accepts a dictionary of employee records and must return a tuple containing the number of records and the average salary. The function should not modify the input dictionary. Which function definition achieves this?
80A developer is writing a function that retrieves a value from a nested dictionary based on a sequence of keys. If any key is missing, the function should raise a custom exception MissingKeyError with the missing key. The function signature is def get_nested(data, keys):. Which implementation correctly meets these requirements?
Deep-dive questions
The most-searched questions in this domain — detailed explanations, worked examples, full answer breakdowns.
Be able to read short Python snippets and state the exact result or exception. The key skill is knowing that tuples cannot be changed after creation and that argument order rules make foo(y=2, 3) a SyntaxError.
The Courseiva PCEP question bank contains 80 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