PCEP · domain
Functions, Tuples, Dictionaries and Exceptions
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.
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
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.
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
Watch out for
Common Functions, Tuples, Dictionaries and Exceptions exam traps
- ▸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
Question index
All Functions, Tuples, Dictionaries and Exceptions questions (80)
Click any question to see the full explanation, or start a practice session above.
Which THREE of the following statements about Python exception handling are correct?
Medium2Which TWO of the following are valid dictionary methods? (Select two.)
Medium3An 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?
Hard4A 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?
Easy5What is the output of the following code? def greet(name, greeting='Hello'): print(greeting, name) greet('Alice')
Easy6What is the output of the following dictionary comprehension? {x: x**2 for x in range(3)}
Medium7Which THREE of the following are valid dictionary methods? (Choose three.)
Medium8A 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?
Medium9A 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?
Medium10A 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?
Hard11Which TWO of the following are true about function arguments in Python? (Choose two.)
Medium12A 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?
Hard13A 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?
Hard14A 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?
Hard15A 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?
Easy16What 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')
Hard17Which of the following will raise a TypeError?
Hard18A 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?
Hard19What happens when you try to modify a tuple? t = (1, 2, 3) t[0] = 0
Easy20A 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?
Medium21A 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.)
Medium22A 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?
Medium23Given a list of names = ['Alice', 'Bob', 'Charlie'], a developer wants to create a dictionary mapping each name to its length. Which expression accomplishes this?
Easy24A 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?
Medium25A function is defined as: def min_max(nums): return min(nums), max(nums). What type of value does it return?
Medium26A 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?
Easy27A 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?
Easy28Which of the following correctly creates a tuple with a single element 5?
Easy29A developer writes a function that takes a tuple as an argument and tries to modify an element inside the tuple. What happens?
Easy30Which exception is raised when trying to access a dictionary key that does not exist?
Hard31A 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?
Easy32Which of the following statements about function arguments are true? (Select all that apply)
Hard33A 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?
Hard34A 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?
Medium35Which TWO of the following statements about tuples in Python are true?
Medium36A developer is writing a function that should accept any number of positional arguments and return their sum. Which function definition correctly achieves this?
Medium37A developer wants to raise a ValueError with a custom message when a negative number is passed. Which code is correct?
Medium38A developer wants to create a tuple containing a single integer value 5. Which code snippet correctly creates such a tuple?
Easy39Which THREE of the following are built-in exceptions in Python? (Select three.)
Easy40A 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?
Easy41A 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?
Hard42A 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?
Medium43Order the steps to create and use a list in Python.
Medium44What 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')
Hard45Consider the code: try: try: raise TypeError except ValueError: print('A') except TypeError: print('B') finally: print('C'). What is printed?
Hard46A 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?
Easy47A 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?
Medium48What is the output of the following code? def test(): try: return 1 finally: return 2 print(test())
Hard49A 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?
Medium50Order the steps to define a class and create an object in Python.
Medium51In 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?
Hard52A 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?
Hard53A 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?
Medium54A 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?
Medium55A 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?
Medium56A developer is using a lambda function that takes two arguments and returns their sum. Which of the following lambda expressions is correct?
Hard57Refer to the exhibit. What is the output when the code is executed?
Hard58A 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)`?
Hard59Which TWO of the following are valid ways to create a dictionary with initial key-value pairs? (Select exactly 2)
Medium60A 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?
Medium61A 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?
Easy62A 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?
Hard63A developer defines a tuple `config = ('localhost', 8080, True)`. Later, the code attempts `config[1] = 9090`. What happens when this line executes?
Medium64A 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?
Easy65A 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?
Easy66A 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?
Medium67A 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?
Easy68A 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.)
Medium69A 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?
Easy70What does the following code output? try: x = int('abc') except ValueError: print('Invalid')
Easy71What is the result of the following expression? d = {'a': 1} d.get('b', 0)
Easy72A 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?
Hard73Which TWO of the following are valid methods that can be called on a tuple object? (Choose two.)
Easy74A 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?
Hard75Given the tuple t = (1, 2, 3, 4, 5), which expression returns the last element?
Medium76Which TWO of the following exceptions are built-in Python exceptions? (Select exactly 2)
Easy77A developer wants to create a tuple that contains a single element, the integer 5. Which of the following expressions produces exactly that?
Hard78A dictionary student = {'name': 'John', 'age': 20}. To safely get the grade with a default of 'N/A', which code should be used?
Easy79A developer needs to determine the number of elements in a tuple named 't'. Which code snippet will correctly return the length?
Easy80Consider the following code: def foo(x, y): return x * y result = foo(y=2, 3) What is the error?
MediumOther domains
All PCEP exam domains
Frequently asked questions
- What does the Functions, Tuples, Dictionaries and Exceptions domain cover on the PCEP exam?
- 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.
- How many questions are in this domain?
- This page lists all 80 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.