Courseiva

PCEP · topic practice

Functions, Tuples, Dictionaries and Exceptions practice questions

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.

Courseiva uses original exam-style practice questions designed for learning and revision. The goal is to understand the concepts, recognise exam patterns, and improve through explanations — not memorise copied exam dumps.

Editorial oversight:Johnson Ajibi· MSc IT Security, IEEE Senior Member
20 questionsDomain: Functions, Tuples, Dictionaries and Exceptions

What the exam tests

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

Practice set

Functions, Tuples, Dictionaries and Exceptions questions

20 questions · select your answer, then reveal the explanation

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?

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?

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?

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?

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

Which THREE of the following dictionary methods return a view object that changes when the dictionary changes?

What is the output of the code?

Exhibit

Refer to the exhibit.

def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return float('inf')
    except TypeError:
        return None

result = divide(10, '5')
print(result)

What is the output of this code?

Exhibit

Refer to the exhibit.

data = {'a': 1, 'b': 2, 'c': 3}
for key, value in data.items():
    if value % 2 == 0:
        data.pop(key)
print(data)

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?

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?

Match each Python function to its description.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Outputs objects to the console

Reads a string from standard input

Returns the number of items in a container

Returns the type of an object

Converts a value to an integer

Match each Python string method to its action.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Converts all characters to uppercase

Converts all characters to lowercase

Removes leading and trailing whitespace

Splits a string into a list of substrings

Joins elements of an iterable into a single string

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

Based on the exhibit, where did the exception originate?

Exhibit

Refer to the exhibit.

Error log output:
Traceback (most recent call last):
  File "app.py", line 10, in <module>
    result = divide(10, 0)
  File "app.py", line 5, in divide
    return a / b
ZeroDivisionError: division by zero

What is the output of the code in the exhibit?

Exhibit

Refer to the exhibit.

def process(data):
    return {item: len(item) for item in data}

print(process(['apple', 'banana', 'cherry']))

What is the output of the code?

Exhibit

Refer to the exhibit.

config = {
    'host': 'localhost',
    'port': 8080,
    'timeout': 30
}

try:
    value = config['debug']
except KeyError:
    print('Key not found')

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

Exhibit

def divide(a, b):
    return a / b

result = divide(10, 0)

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

Exhibit

d = {'a':1, 'b':2}
for k, v in d.items():
    if k == 'a':
        del d[k]
print('done')

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

Which code sorts a list of strings by their length in descending order?

lst = ['aa', 'b', 'ccc']

Free account

Track your progress over time

Create a free account to save your results and see which topics improve across sessions.

Focused Functions, Tuples, Dictionaries and Exceptions sessions

Start a Functions, Tuples, Dictionaries and Exceptions only practice session

Every question in these sessions is drawn from the Functions, Tuples, Dictionaries and Exceptions domain — nothing else.

Related practice questions

Related PCEP topic practice pages

Move into related areas when this topic feels solid.

Frequently asked questions

What does the PCEP exam test 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.
How should I use these practice questions?
Select your answer before revealing the explanation. Then read why each option is right or wrong — this active recall approach builds retention far faster than re-reading notes.
Can I practise just Functions, Tuples, Dictionaries and Exceptions questions in a focused session?
Yes — the session launcher on this page draws every question from the Functions, Tuples, Dictionaries and Exceptions domain. Use a 10-question session first to gauge your baseline, then move to 20 or 30 once the weak spots are clear.
Where can I practise other PCEP topics?
Use the topic links above to move to related areas, or go back to the PCEP question bank to see all topics.
Are these real exam questions or dumps?
These are original practice questions written to test the same concepts the PCEP exam covers. They are not copied from any real exam or dump site.