Courseiva

CCNA Functions, Tuples, Dictionaries and Exceptions Questions

75 of 82 questions · Page 1/2 · Functions, Tuples, Dictionaries and Exceptions · Answers revealed

1
Multi-Selectmedium

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

Select 3 answers
A.The finally block always runs.
B.The else block runs if no exception occurred.
C.You must have at least one except block if you have a finally block.
D.You can have multiple except blocks for different exception types.
E.A try block must have at least one except block.
AnswersA, B, D

The finally clause executes regardless of whether an exception occurred or not.

Why this answer

The `finally` block in Python is guaranteed to execute regardless of whether an exception occurred, was caught, or even if the `try` block contains a `return`, `break`, or `continue` statement. This ensures cleanup actions like closing files or releasing resources always run.

Exam trap

The PCEP exam often tests the misconception that a `finally` block requires an accompanying `except` block, or that a `try` block must always have at least one `except` block, when in fact `try-finally` alone is valid Python syntax.

2
MCQeasy

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?

A.Return None if any non-numeric value is encountered.
B.Use try-except to ignore non-numeric values and proceed with the remaining numbers.
C.Convert all values to string and concatenate them.
D.Check that all items are numeric before calculation, and raise TypeError otherwise.
AnswerD

Raising an exception is the standard way to handle invalid input.

Why this answer

It explicitly validates that all items are numeric before performing the calculation, raising a TypeError if any non-numeric value is found. This follows Python's principle of explicit error handling and ensures the function's contract is clear: it only works with numeric data. Returning None (A) or silently ignoring values (B) can lead to subtle bugs, while converting to strings (C) would produce a concatenated string, not an average.

Exam trap

Python Institute often tests the distinction between silently handling errors (e.g., returning None or ignoring bad data) and explicitly raising exceptions, where candidates may mistakenly choose a 'graceful' option like ignoring non-numeric values, not realizing that it can lead to incorrect results without any warning.

How to eliminate wrong answers

Option A is wrong because returning None when encountering non-numeric values silently changes the return type, which can cause downstream code to fail unexpectedly (e.g., when trying to use the result in further arithmetic). Option B is wrong because using try-except to ignore non-numeric values silently discards data, producing an average that may be misleadingly incorrect without any indication of the omission. Option C is wrong because converting all values to strings and concatenating them produces a string, not a numeric average, which is a fundamental type error and completely misses the purpose of the function.

3
MCQeasy

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

A.Hello
B.Hello Alice
C.SyntaxError
D.Alice
AnswerB

Correct because the default greeting is used.

Why this answer

The function `greet` has a default parameter `greeting='Hello'`. When called with only one argument (`'Alice'`), the default value is used for `greeting`, so the output is `Hello Alice`. The `print` function outputs both arguments separated by a space.

Exam trap

Python Institute often tests whether candidates understand that default parameters are used when the corresponding argument is omitted, leading to the misconception that only the default value is printed or that a syntax error occurs.

How to eliminate wrong answers

Option A is wrong because it omits the name argument; the function prints both the greeting and the name, not just the greeting. Option C is wrong because the function definition is syntactically valid (default parameters are allowed in Python) and the call with one argument matches the required parameter. Option D is wrong because it only prints the name, ignoring the default greeting that is explicitly printed.

4
MCQmedium

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

A.{0:0, 1:1, 2:4}
B.{0:1, 1:2, 2:3}
C.{0:0, 1:2, 2:4}
D.{1:1, 2:4}
AnswerA

Correct.

Why this answer

The dictionary comprehension `{x: x**2 for x in range(3)}` iterates over `x` values 0, 1, and 2 (from `range(3)`). For each `x`, it creates a key-value pair where the key is `x` and the value is `x**2` (x squared). This produces `{0: 0**2, 1: 1**2, 2: 2**2}`, which evaluates to `{0:0, 1:1, 2:4}`.

Exam trap

Python Institute often tests whether candidates remember that `range(3)` starts at 0, not 1, and that `0**2` equals 0, not an omitted or undefined value, causing many to drop the first key-value pair or miscalculate the square of 1.

How to eliminate wrong answers

Option B is wrong because it incorrectly maps each `x` to `x+1` (0→1, 1→2, 2→3), which is not what `x**2` computes. Option C is wrong because it shows `1:2` instead of `1:1`, likely confusing `x**2` with `x*2` (multiplication) or miscomputing `1**2` as 2. Option D is wrong because it omits the key `0` entirely, which would only happen if the comprehension started from `range(1,3)` or if the candidate mistakenly thought `0**2` is undefined or should be skipped.

5
Multi-Selectmedium

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

Select 3 answers
A..values()
B..append()
C..push()
D..keys()
E..get()
AnswersA, D, E

values returns a view of dictionary values.

Why this answer

The `.values()` method returns a view object that displays a list of all the values in a dictionary. It is a built-in dictionary method in Python, making option A correct.

Exam trap

The PCEP exam often tests the distinction between list methods (like `.append()`) and dictionary methods, trapping candidates who confuse data structure operations across types.

6
MCQhard

What is the output of this code?

A.RuntimeError: dictionary changed size during iteration
B.{}
C.{'b': 2}
D.{'a': 1, 'c': 3}
AnswerA

Modifying dict while iterating over its items raises RuntimeError.

Why this answer

Modifying a dictionary's size (adding or deleting keys) during iteration over its keys, values, or items raises a RuntimeError. In this code, the loop iterates over the dictionary's keys while deleting them, which changes the dictionary's size and triggers the exception.

Exam trap

Python Institute often tests the misconception that deleting keys during iteration will silently skip or partially modify the dictionary, but Python explicitly forbids size changes during iteration to enforce safe iteration contracts.

How to eliminate wrong answers

Option B is wrong because the code never completes execution to produce an empty dictionary; the RuntimeError is raised before any deletion finishes. Option C is wrong because the loop is interrupted by the exception before it can delete all keys except 'b', so no partial result is returned. Option D is wrong because the original dictionary is never returned; the iteration is aborted at the first deletion, and the exception prevents any output.

7
MCQhard

Refer to the exhibit. What is the output?

A.{'key': 'old_value'}
B.{'another': 'dict'}
C.None
D.{'key': 'new_value'}
AnswerD

Correct. The original dictionary is mutated.

Why this answer

The `update()` method on a dictionary modifies the dictionary in place by updating the value for an existing key. Since `my_dict` already contains the key `'key'`, calling `update({'key': 'new_value'})` changes its value to `'new_value'`, and the method returns `None`. The print statement outputs the updated dictionary, which is `{'key': 'new_value'}`.

Exam trap

The PCEP exam often tests the distinction between a method's return value and the object it modifies, leading candidates to mistakenly think the output is `None` (the return value of `update()`) instead of the updated dictionary itself.

How to eliminate wrong answers

Option A is wrong because it shows the old value `'old_value'`, but the `update()` method replaces the value for the existing key, so the output reflects the new value. Option B is wrong because it shows a completely different dictionary `{'another': 'dict'}`, which would only appear if the `update()` method were called with a different key or if the dictionary were reassigned entirely. Option C is wrong because although `update()` returns `None`, the print statement prints `my_dict` itself, not the return value of `update()`, so the output is the updated dictionary, not `None`.

8
MCQmedium

Refer to the exhibit. What is the output?

A.A C D
B.B C D
C.A B C D
D.A C
AnswerA

Correct. First 'A', then 'C', then 'D'.

Why this answer

The code defines a tuple containing numbers 1, 3, and 4 (e.g., `t = (1, 3, 4)`) and a dictionary `d = {'A': 1, 'B': 2, 'C': 3, 'D': 4}`. The `for` loop iterates over dictionary keys. The condition `if d[k] in t` checks if the associated value is in the tuple.

Values 1, 3, and 4 are present, so keys A, C, and D are printed. Value 2 is absent, so B is not printed. The output is A, C, D each on a new line, matching option A.

Exam trap

A common pitfall in Python PCEP exams is that dictionary iteration yields keys, but candidates may mistakenly think it yields values, or that the `in` operator checks keys rather than values, leading to incorrect filtering.

How to eliminate wrong answers

Option A (A, C, D) is wrong because it omits 'B', but the value 2 for key 'B' is in the tuple (1,2,3,4,5), so 'B' should be printed. Option B (B, C, D) is wrong because it omits 'A', but the value 1 for key 'A' is in the tuple, so 'A' should be printed. Option D (A, C) is wrong because it omits both 'B' and 'D', but both values 2 and 4 are in the tuple, so 'B' and 'D' should be printed.

9
MCQeasy

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?

A.Use a namedtuple and use the _replace() method to create a new instance with the updated port
B.Replace the entire tuple with a list to allow updates
C.Store all parameters in a dictionary and update the port as needed
D.Convert the tuple to a list, update the port, then convert back to a tuple each time
AnswerC

A dictionary is mutable and allows easy updates while clearly showing which parameters are changeable.

Why this answer

A dictionary allows direct mutation of the port value without affecting the immutability of other parameters. This satisfies the requirement of changing only the port at runtime while keeping the rest of the configuration unchanged, and it minimizes code changes by simply replacing the tuple with a dict and using assignment to update the port key.

Exam trap

The trap here is that candidates assume namedtuple._replace() mutates the tuple in place, but it actually returns a new instance, which does not satisfy the requirement for runtime mutation without restarting the script.

How to eliminate wrong answers

Option A is wrong because namedtuple._replace() creates a new namedtuple instance, which does not mutate the original tuple; this approach still requires reassigning the variable and does not allow in-place mutation of a single element, so it does not meet the 'changeable at runtime' requirement without restarting the script. Option B is wrong because replacing the entire tuple with a list makes all parameters mutable, violating the requirement that other parameters remain immutable. Option D is wrong because repeatedly converting between tuple and list is inefficient, adds unnecessary complexity, and still makes all parameters mutable during the list phase, breaking immutability for the other parameters.

10
MCQhard

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?

A.Use a set for each value to avoid duplicates
B.Use a dictionary of lists with a default factory (e.g., collections.defaultdict(list))
C.Use a list for each value, and append new values to the list
D.Use a tuple for each value, converting to list when needed
AnswerB

Using a dictionary of lists with a default factory (e.g., collections.defaultdict(list)) automatically creates a new list for each new key, allowing multiple values to be appended without overwriting. This preserves all values for a key efficiently for both adding and retrieving.

Why this answer

`collections.defaultdict(list)` automatically creates a new list for each new key, allowing multiple values to be appended without overwriting. This preserves all values for a key while providing O(1) average-time access to the list of values, meeting the efficiency requirement for both adding and retrieving.

Exam trap

The trap here is that candidates think Option C is sufficient on its own, overlooking that `defaultdict` provides automatic initialization, which is the key efficiency improvement tested in the PCEP exam.

How to eliminate wrong answers

Option A is wrong because using a set for each value would deduplicate entries, which is not required and would lose legitimate duplicate values from different sources (e.g., the same DNS server from DHCP and manual config). Option C is wrong because while appending to a list works, it requires manually checking if the key exists and initializing a list for each new key, which is less efficient and more error-prone than using a defaultdict. Option D is wrong because tuples are immutable; converting to a list for each append operation introduces unnecessary overhead and complexity, and the tuple would need to be replaced entirely on each addition.

11
MCQhard

Refer to the exhibit. What is the output?

A.1 2 --- 1
B.1 2 3 --- 1
C.1 2 3 --- 1 2 3
D.1 --- 1
AnswerB

Correct. First loop prints all three, second loop prints only first then breaks.

Why this answer

The code defines a tuple t = (1, 2, 3) and iterates over it with a single for loop, printing each element on a separate line. After the loop, it prints a separator line of dashes (---) and then prints the first element t[0] which is 1. The output is therefore 1, 2, 3, ---, 1 — exactly matching option B.

Exam trap

The PCEP exam often tests the distinction between iterating over all elements of a tuple versus accessing a single element by index, leading candidates to mistakenly think the final print repeats the entire loop or that the loop stops early.

How to eliminate wrong answers

Option A is wrong because it omits the third element `3` from the loop output, suggesting the loop only iterated twice or that the tuple had only two elements. Option C is wrong because it prints `1 2 3` again after the separator, implying the loop ran again or that the final print statement iterated over the entire tuple instead of accessing only index 0. Option D is wrong because it shows only the first element `1` from the loop and then the final `1`, completely missing the second and third elements, as if the loop only executed once or the tuple contained only one element.

12
Multi-Selectmedium

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

Select 2 answers
A.Arguments can be passed by position or keyword.
B.Default arguments are evaluated each time the function is called.
C.*args collects keyword arguments.
D.**kwargs collects positional arguments.
E.Default arguments are evaluated at function definition time.
AnswersA, E

Correct: Python supports both positional and keyword arguments.

Why this answer

Python allows function arguments to be passed either by position (matching the order of parameters in the function definition) or by keyword (using the parameter name explicitly). This flexibility is a core feature of Python's function call semantics, enabling clearer and more flexible code.

Exam trap

The PCEP exam often tests the distinction between *args (positional) and **kwargs (keyword) and the timing of default argument evaluation, hoping candidates confuse the asterisk syntax or assume defaults are re-evaluated on each call.

13
MCQhard

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?

A.Change the bare except: to except Exception:
B.Remove the except block entirely and rely on a finally block for cleanup
C.Replace the single except block with multiple specific except blocks for each expected file error
D.Define a custom exception class and raise it for all file errors
AnswerA

except Exception: catches all exceptions that inherit from Exception, excluding KeyboardInterrupt and SystemExit.

Why this answer

Changing the bare `except:` to `except Exception:` ensures that only exceptions inheriting from the built-in `Exception` class are caught. System-exiting exceptions like `KeyboardInterrupt` and `SystemExit` inherit from `BaseException` directly, not from `Exception`, so they will propagate uncaught, allowing a clean exit. This preserves the cleanup behavior for file-related errors such as `FileNotFoundError` and `PermissionError`, which are subclasses of `Exception`.

Exam trap

The PCEP exam often tests the misconception that a bare `except:` is equivalent to `except Exception:`, when in fact it catches all `BaseException` subclasses, including `KeyboardInterrupt` and `SystemExit`, which should typically be allowed to terminate the program.

How to eliminate wrong answers

Option B is wrong because removing the `except` block entirely and relying solely on a `finally` block would not handle any exceptions at all; the program would crash on file errors without performing the intended cleanup. Option C is wrong because while multiple specific `except` blocks for file errors would work, they do not address the requirement to avoid catching system-exiting exceptions; a bare `except:` would still be needed for unexpected errors, which would again catch `KeyboardInterrupt`. Option D is wrong because defining a custom exception class and raising it for all file errors does not change which exceptions are caught by the existing bare `except:` clause; the bare `except:` would still catch `KeyboardInterrupt` and `SystemExit`.

14
MCQhard

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?

A.Use a single bare except: clause
B.Use except: and then re-raise the exception
C.Use multiple except blocks for specific exception types
D.Use except Exception: as the only handler
AnswerC

This targets only the expected exceptions, letting others propagate as intended.

Why this answer

Using multiple `except` blocks for specific exception types (e.g., `FileNotFoundError`, `PermissionError`) allows the script to catch only I/O-related exceptions while letting all other exceptions propagate unhandled. This matches the requirement precisely, as each `except` clause targets a distinct exception class, and any unlisted exception will not be caught, preserving the intended error propagation behavior.

Exam trap

The PCEP exam often tests the misconception that a single `except Exception:` is sufficient for selective handling, but candidates fail to realize it catches all `Exception` subclasses, including non-I/O ones, thus violating the requirement to let other exceptions propagate.

How to eliminate wrong answers

Option A is wrong because a single bare `except:` clause catches all exceptions, including non-I/O ones like `KeyboardInterrupt` or `SystemExit`, which violates the requirement to let other exceptions propagate. Option B is wrong because using `except:` and then re-raising the exception still catches all exceptions initially, which is unnecessary and can mask the intent; it also does not selectively handle only I/O exceptions. Option D is wrong because `except Exception:` catches all subclasses of `Exception`, which includes many non-I/O exceptions (e.g., `ValueError`, `TypeError`), failing to let those propagate as required.

15
MCQhard

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?

A.Use copy.deepcopy() from the copy module
B.Assign the dictionary to a new variable (e.g., new_dict = original)
C.Use copy.copy() on the original dictionary
D.Use dict.copy() method
AnswerA

Deep copy recursively copies all objects, making the new dictionary completely independent.

Why this answer

`copy.deepcopy()` recursively copies all objects within the dictionary, including nested dictionaries, creating a completely independent copy. This ensures modifications to the copy do not affect the original argument, which is required when the dictionary contains mutable nested structures.

Exam trap

The PCEP exam often tests the distinction between shallow and deep copies, and the trap here is that candidates assume `dict.copy()` or `copy.copy()` create a full independent copy, overlooking that nested dictionaries remain shared references.

How to eliminate wrong answers

Option B is wrong because assigning the dictionary to a new variable (e.g., `new_dict = original`) only creates a new reference to the same dictionary object, not a copy; any modification to `new_dict` directly mutates the original. Option C is wrong because `copy.copy()` performs a shallow copy, which duplicates the top-level dictionary but shares references to nested dictionaries, so changes to nested structures still affect the original. Option D is wrong because `dict.copy()` also performs a shallow copy, identical to `copy.copy()`, and does not handle nested dictionaries independently.

16
MCQhard

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

A.Error: division by zero
B.Zero division
C.TypeError
D.Invalid division
AnswerD

Correct; the ValueError is raised and caught.

Why this answer

The `div` function catches the `ZeroDivisionError` and raises a `ValueError` with the message 'Invalid division'. The outer `try` block catches this `ValueError` and prints its message, which is 'Invalid division'.

Exam trap

The PCEP exam often tests the distinction between catching an exception and raising a different exception inside the handler, tricking candidates into thinking the original exception type (ZeroDivisionError) will still be caught by the outer handler.

How to eliminate wrong answers

Option A is wrong because the code does not print an 'Error: division by zero' message; the `ZeroDivisionError` is caught inside `div` and replaced with a `ValueError`. Option B is wrong because the outer `except ZeroDivisionError` clause is never triggered; the raised exception is a `ValueError`, not a `ZeroDivisionError`. Option C is wrong because no `TypeError` occurs; the division operation is valid in terms of types (both are integers), and the exception handling is correctly structured.

17
MCQhard

Which of the following will raise a TypeError?

A.t = (1, 2); t[0] = 3
B.lst = [1, 2]; lst.extend([3, 4])
C.x = {1, 2} & {2, 3}
D.d = {'a': 1}; d['b'] = 2
AnswerA

Tuples are immutable; assignment to element raises TypeError.

Why this answer

Tuples are immutable in Python; attempting to assign a value to an element using indexing (e.g., `t[0] = 3`) raises a `TypeError` with the message 'tuple' object does not support item assignment. This is a fundamental property of the tuple data type, designed to create fixed sequences that cannot be changed after creation.

Exam trap

Python Institute often tests the distinction between mutable and immutable types, specifically that tuples cannot be modified after creation, while lists, sets, and dictionaries can be changed via their respective methods or assignments.

How to eliminate wrong answers

Option B is wrong because `lst.extend([3, 4])` is a valid list method that appends all elements from the iterable `[3, 4]` to the end of the list, modifying it in place without error. Option C is wrong because `x = {1, 2} & {2, 3}` performs a set intersection operation, which is perfectly valid and returns a new set `{2}`; no TypeError occurs. Option D is wrong because `d['b'] = 2` assigns a new key-value pair to the dictionary, which is a standard and allowed operation on mutable dictionaries.

18
MCQeasy

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

A.A TypeError is raised
B.A IndexError is raised
C.The tuple becomes (0, 2, 3)
D.The code runs without error
AnswerA

Correct; assignment to tuple element raises TypeError.

Why this answer

Tuples are immutable, so trying to assign to an index raises a TypeError.

19
MCQeasy

What is the output of the code?

A.AttributeError
B.The program exits with no output
C.None
D.Key not found
AnswerD

The get() method returns the default value 'Key not found' when the key is absent, so this is printed.

Why this answer

The code uses a dictionary's `get()` method with a default value of 'Key not found'. When the key 'b' is not present in the dictionary `d`, `get()` returns the specified default instead of raising an exception. Therefore, the output is 'Key not found', making option D correct.

Exam trap

The PCEP exam often tests the distinction between `dict[key]` (which raises `KeyError`) and `dict.get(key, default)` (which returns the default), trapping candidates who expect an exception or assume the default is `None`.

How to eliminate wrong answers

Option A is wrong because `get()` does not raise an `AttributeError`; it is a built-in dictionary method that safely handles missing keys. Option B is wrong because the program does not exit silently; `print()` always outputs something, and in this case it outputs the default value. Option C is wrong because `None` would only be returned if no default argument were provided to `get()`; here the explicit default 'Key not found' overrides that behavior.

20
MCQhard

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.The dictionary is being modified concurrently by multiple threads or processes without synchronization, leading to race conditions.
B.The function catches KeyError and silently returns without completing the transfer.
C.The function does not check if the from_acc has sufficient balance before subtracting.
D.The balances are stored as strings instead of floats, causing concatenation instead of arithmetic.
AnswerA

Race condition can cause the second update to be lost.

Why this answer

The described symptom — the `from_acc` balance is reduced but the `to_acc` balance is not increased — is a classic race condition. In Python, dictionary operations like `dict[key] -= amount` are not atomic; they involve a read, modify, and write sequence. If two threads execute the transfer function concurrently on overlapping accounts, one thread's write to `to_acc` can be overwritten by another thread's stale read, causing the addition to be lost.

The `try-except` only catches `KeyError`, not data races, and since no exception is raised, the only plausible explanation is unsynchronized concurrent access.

Exam trap

Python Institute often tests the misconception that Python's GIL prevents all concurrency issues, but the trap here is that the GIL does not make compound operations atomic, so race conditions can still occur with dictionary updates.

How to eliminate wrong answers

Option B is wrong because the problem states that no exceptions are raised during the problematic transfers, so the function is not silently returning due to a caught KeyError; the transfers proceed but produce incorrect balances. Option C is wrong because insufficient balance would cause a negative balance in `from_acc`, but the symptom is that `to_acc` is not increased — the subtraction from `from_acc` works correctly, so the issue is not about balance checking. Option D is wrong because if balances were stored as strings, the subtraction operation (`-=`) would raise a TypeError, not silently produce incorrect results; the problem states no exceptions occur, so the types must be correct.

21
MCQeasy

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

A.The function is not defined before the call.
B.The variable 'result' is not defined.
C.The function parameters are of incompatible types.
D.The function does not have a return statement.
AnswerD

The function computes the sum but does not return it, returning None instead.

Why this answer

The function `add` computes `a + b` and assigns it to `result`, but lacks a `return` statement. In Python, a function without an explicit `return` automatically returns `None`. When `print(add(3, 4))` is executed, it prints `None`, not the sum.

The question states the code returns 0, which is a common misreading — the actual output is `None`, but the core issue is the missing `return`.

Exam trap

Python Institute often tests the distinction between computing a value inside a function and actually returning it — the trap here is that candidates see `result = a + b` and assume the sum is automatically output, missing the critical absence of the `return` statement.

How to eliminate wrong answers

Option A is wrong because the function is defined before the call (the definition appears on lines 1-2, and the call is on line 4). Option B is wrong because `result` is defined inside the function (line 2), so it exists in the local scope; the problem is that it is never returned. Option C is wrong because both parameters are integers (3 and 4), which are compatible types for the `+` operator; no TypeError would occur.

22
MCQeasy

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?

A.{len(name): name for name in names}
B.{name: len(name) for name in names}
C.{name: len for name in names}
D.{name: length for name in names}
AnswerB

Correct: This comprehension creates the mapping with each name and its length.

Why this answer

It uses a dictionary comprehension that iterates over each name in the list, using the name as the key and the result of `len(name)` as the value. This directly maps each name to its length, which is exactly what the developer wants.

Exam trap

The trap here is that candidates may confuse the key-value order in a dictionary comprehension or forget to call `len()` as a function, leading them to pick options that either swap the mapping or use an undefined variable.

How to eliminate wrong answers

Option A is wrong because it uses `len(name)` as the key and `name` as the value, which would create a dictionary mapping lengths to names (e.g., {5: 'Alice', 3: 'Bob', 7: 'Charlie'}), not names to lengths. Option C is wrong because `len` is a function object, not a function call; it would store the function itself as the value for each name, not the length of the name. Option D is wrong because `length` is an undefined variable; it would raise a NameError at runtime, as there is no variable named `length` in scope.

23
MCQmedium

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

A.A tuple
B.A set
C.A dictionary
D.A list
AnswerA

Correct: Multiple return values without brackets form a tuple.

Why this answer

The function `min_max` uses `return min(nums), max(nums)`, which is a comma-separated list of expressions. In Python, when multiple values are returned separated by commas, they are automatically packed into a tuple. Therefore, the function returns a tuple containing the minimum and maximum values.

Exam trap

The PCEP exam often tests the misconception that multiple return values are returned as a list or that parentheses are required to create a tuple, but in Python, it is the comma that defines a tuple, not the parentheses.

How to eliminate wrong answers

Option B is wrong because a set is created with curly braces or the `set()` constructor, and returning values separated by commas does not produce a set. Option C is wrong because a dictionary requires key-value pairs, but the function returns two values without any keys. Option D is wrong because a list is created with square brackets, and the comma syntax in a return statement does not produce a list.

24
Matchingmedium

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

Why these pairings

These are common built-in Python functions. len() returns length, print() outputs, int() converts to integer, str() converts to string, and input() reads user input.

25
MCQmedium

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.result = func(); a, b = result[0], result[1]
B.a, b, c = func()
C.a = func()[0]; b = func()[1]
D.a, b = func()
AnswerD

This is direct tuple unpacking.

Why this answer

When a function returns multiple values as a tuple, Python allows tuple unpacking directly in an assignment statement. The syntax `a, b = func()` automatically unpacks the two-element tuple into the variables `a` and `b`, which is the standard and most Pythonic way to handle such a return.

Exam trap

Python Institute often tests the requirement that the number of variables on the left must exactly match the number of elements in the returned tuple, so candidates who choose option B fall into the trap of assuming extra variables are simply ignored or set to `None`.

How to eliminate wrong answers

Option A is wrong because while it technically works, it is unnecessarily verbose and not the standard unpacking syntax; it manually indexes the tuple, which defeats the purpose of Python's built-in unpacking feature. Option B is wrong because it attempts to unpack a two-element tuple into three variables, which will raise a `ValueError: too many values to unpack (expected 3)` at runtime. Option C is wrong because it calls `func()` twice, which is inefficient and may cause side effects if the function has state or performs I/O; additionally, it does not use tuple unpacking at all.

26
MCQeasy

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

A.t = (5,)
B.t = (5)
C.t = (5)
D.t = (5, 5)
AnswerA

Correct. The trailing comma is required to create a single-element tuple.

Why this answer

In Python, a tuple with a single element requires a trailing comma after the element. Without the comma, parentheses are treated as grouping operators for expression evaluation, not as a tuple literal. Thus, `t = (5,)` creates a tuple containing the integer 5.

Exam trap

The trap here is that candidates mistakenly believe parentheses alone create a tuple, overlooking the mandatory trailing comma for single-element tuples, which Cisco tests to distinguish between tuple creation and simple expression grouping.

How to eliminate wrong answers

Option B is wrong because `t = (5)` does not create a tuple; the parentheses are interpreted as grouping, so `t` becomes the integer 5. Option C is identical to B and also wrong for the same reason. Option D is wrong because `t = (5, 5)` creates a tuple with two elements, not a single element.

27
MCQeasy

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

A.The code raises a TypeError.
B.The tuple is converted to a list automatically.
C.The first element is modified successfully.
D.The code raises a ValueError.
AnswerA

Tuples do not support item assignment.

Why this answer

Tuples in Python are immutable, meaning their elements cannot be changed after creation. Attempting to modify an element (e.g., `my_tuple[0] = 5`) raises a `TypeError` because the tuple object does not support item assignment. This is a fundamental property of the tuple data type.

Exam trap

Python Institute often tests the distinction between `TypeError` and `ValueError` — the trap here is that candidates may confuse an operation that is not allowed (TypeError) with an operation that receives an invalid value (ValueError).

How to eliminate wrong answers

Option B is wrong because Python never automatically converts a tuple to a list when modification is attempted; such an operation simply raises an error. Option C is wrong because tuples are immutable, so no element can be modified successfully. Option D is wrong because a `ValueError` is raised for inappropriate values, not for operations that are not supported by the object type; the error here is a `TypeError`.

28
MCQhard

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

A.KeyError
B.TypeError
C.ValueError
D.AttributeError
AnswerA

Accessing a missing key raises KeyError.

Why this answer

In Python, when you attempt to access a dictionary key that does not exist using square bracket notation (e.g., `my_dict['nonexistent']`), the interpreter raises a `KeyError`. This is the standard exception for missing dictionary keys, as defined in the Python language specification. The correct answer is A.

Exam trap

Python Institute often tests whether candidates confuse `KeyError` with `ValueError` or `TypeError`, especially when the question involves dictionary operations like `pop()` or `del` on a missing key, where the same `KeyError` is raised.

How to eliminate wrong answers

Option B (TypeError) is wrong because `TypeError` occurs when an operation or function is applied to an object of inappropriate type (e.g., adding a string to an integer), not when a key is missing from a dictionary. Option C (ValueError) is wrong because `ValueError` is raised when a function receives an argument with the right type but an inappropriate value (e.g., `int('abc')`), not for missing dictionary keys. Option D (AttributeError) is wrong because `AttributeError` occurs when an invalid attribute reference or assignment is made (e.g., `None.some_method`), not when accessing a non-existent dictionary key.

29
MCQhard

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.count = logs.count(('ERROR',))
B.count = sum(log[1] == 'ERROR' for log in logs)
C.count = [log for log in logs if log[1] == 'ERROR']
D.count = len(logs)
AnswerB

Sum of booleans gives the count.

Why this answer

Uses a generator expression with `sum()` to count how many tuples in the `logs` list have the second element equal to `'ERROR'`. The expression `log[1] == 'ERROR'` evaluates to `True` (which is treated as 1) or `False` (0) for each tuple, and `sum()` adds them up, giving the correct count of ERROR logs.

Exam trap

Python Institute often tests the distinction between `list.count()` (which requires an exact match of the entire element) and counting via a conditional expression with `sum()`, leading candidates to mistakenly think `count()` can filter by a partial tuple or a specific field.

How to eliminate wrong answers

Option A is wrong because `list.count()` counts exact matches of the provided argument; `logs.count(('ERROR',))` looks for a tuple containing only `'ERROR'`, but each log entry is a 3-element tuple, so no match is found and the count is always 0. Option C is wrong because it creates a list of matching tuples, not a count; it would require `len()` to get the number, and the question asks for a code snippet that counts, not just filters. Option D is wrong because `len(logs)` returns the total number of log entries (2), not the count of ERROR logs.

30
Multi-Selecthard

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

Select 4 answers
A.Keyword arguments can be passed in any order, regardless of their position in the function definition.
B.Using **kwargs allows passing a variable number of keyword arguments.
C.The *args parameter must always come after **kwargs in a function definition.
D.Using *args in a function definition allows passing a variable number of positional arguments.
E.Default arguments are evaluated once when the function is defined, not each time it is called.
AnswersA, B, D, E

Keyword arguments can be specified in any order after positional arguments.

Why this answer

The correct statements are A, B, D, and E. Keyword arguments can be passed in any order because they are matched by name (A). The **kwargs parameter collects additional keyword arguments into a dictionary (B).

The *args parameter collects additional positional arguments into a tuple (D). Default arguments are evaluated once at function definition time (E). Option C is incorrect because *args must always appear before **kwargs in a function definition.

Exam trap

A common pitfall in the PCEP exam is the order of *args and **kwargs: *args must precede **kwargs. Also, candidates often incorrectly think default arguments are evaluated each call, but they are evaluated once at definition time.

31
MCQmedium

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?

A.Use `counts.setdefault('apple', 0)` then increment.
B.Use `try-except` to catch KeyError and then set the key.
C.Use `counts['apple'] = counts.get('apple') + 1`
D.Use `if 'apple' in counts:` before incrementing.
AnswerA

setdefault initializes if missing, then increment.

Why this answer

`setdefault('apple', 0)` inserts the key with a default value of 0 if it does not exist, then returns the value (0). After that, `counts['apple'] += 1` increments safely. This avoids a KeyError without requiring an explicit check or exception handling, making it the most concise and Pythonic approach for initializing missing dictionary keys.

Exam trap

Python Institute often tests the misconception that `dict.get()` can be used directly in an increment expression, but candidates forget that `get` returns `None` for missing keys, leading to a TypeError rather than a KeyError.

How to eliminate wrong answers

Option B is wrong because while a try-except block can catch the KeyError, it is less efficient and more verbose than using `setdefault` or `defaultdict`; it also requires two separate operations (catch and set) instead of a single atomic method. Option C is wrong because `counts.get('apple')` returns `None` when the key is missing, and `None + 1` raises a TypeError, not a KeyError. Option D is wrong because it requires an explicit membership test and an extra assignment, which is more code and less efficient than `setdefault`; it also introduces a race condition in multithreaded contexts.

32
MCQhard

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

A.Prints 'done' with no error
B.RuntimeError: dictionary changed size during iteration
C.KeyError: 'a'
D.Nothing; the code runs silently
AnswerB

Correct: The dictionary size changed during iteration.

Why this answer

Modifying a dictionary (adding or deleting keys) while iterating over it with a for loop raises a RuntimeError in Python. The code attempts to delete keys from the dictionary `d` during iteration, which changes the dictionary's size and triggers the error before 'done' is printed.

Exam trap

The PCEP exam often tests the misconception that deleting dictionary keys during iteration is safe or only causes a KeyError, when in fact Python explicitly raises a RuntimeError to prevent undefined behavior.

How to eliminate wrong answers

Option A is wrong because the code raises a RuntimeError before reaching the print('done') statement, so 'done' is never printed. Option C is wrong because the error is not a KeyError; the deletion `del d[k]` uses the current key `k`, which exists at that moment, so no KeyError occurs. Option D is wrong because the code does not run silently; it explicitly raises a RuntimeError due to dictionary size change during iteration.

33
MCQmedium

Refer to the exhibit. What is the output?

A.Done
B.Success\nDone
C.Key missing\nDone
D.Key missing\nSuccess\nDone
AnswerC

Why this answer

The code attempts to access a dictionary key ('key') that does not exist, which raises a KeyError. The except block catches this specific exception and prints 'Key missing'. After the try-except, the 'finally' block (or code after the try-except) prints 'Done'.

The output is therefore 'Key missing' followed by 'Done' on separate lines.

Exam trap

The PCEP exam often tests the order of execution in try-except blocks, specifically that the except block runs only when the matching exception occurs, and that code after the try-except always runs unless a break/return/exit occurs.

How to eliminate wrong answers

Option A is wrong because it ignores the exception handling entirely; the KeyError is raised and caught, so 'Done' alone is not the output. Option B is wrong because it suggests 'Success' is printed, but no success message is defined in the code; the try block fails before any success print. Option D is wrong because it includes 'Success' in the output, but the code never prints 'Success' — the try block raises an exception immediately on the failed key access.

34
MCQhard

Based on the exhibit, where did the exception originate?

A.At line 5 in the divide function inside app.py.
B.In the main module outside any function.
C.In the ZeroDivisionError exception handler.
D.At line 10 in app.py, where the function was called.
AnswerA

The traceback shows the exception was raised at line 5, inside the divide function.

Why this answer

The exception (ZeroDivisionError) originates at line 5 inside the divide function in app.py, where the code attempts to divide by zero. The traceback shows the innermost frame first, indicating the exact line where the error was raised.

Exam trap

The PCEP exam often tests the misconception that an exception originates at the line where the function is called (the call site) rather than inside the function where the actual erroneous operation occurs, leading candidates to pick the call site line instead of the function's internal line.

How to eliminate wrong answers

Option B is wrong because the exception did not originate in the main module outside any function; it was raised inside the divide function. Option C is wrong because the exception handler is not where the exception originates; it is where the exception is caught, not raised. Option D is wrong because line 10 is where the divide function was called, but the actual division by zero occurs inside the function at line 5, not at the call site.

35
MCQmedium

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?

A.Use a tuple as default
B.Use an empty list as default
C.Use None as default and create a new list inside the function
D.Use a global variable as default
AnswerC

This pattern avoids mutable default arguments by creating a fresh list each call.

Why this answer

Using `None` as a default parameter and creating a new list inside the function ensures that the original list passed as an argument is never mutated. In Python, default arguments are evaluated only once at function definition time, so using a mutable default like an empty list can cause unintended side effects across multiple calls. By creating a new list inside the function (e.g., `result = list(original)`), the function operates on a copy, leaving the original list unchanged.

Exam trap

The PCEP exam often tests the classic Python pitfall of mutable default arguments, where candidates mistakenly believe that an empty list default is reset on each call, not realizing it is a single object shared across all invocations.

How to eliminate wrong answers

Option A is wrong because using a tuple as a default does not prevent side effects on the original list argument; the function would still receive the original list and could modify it. Option B is wrong because using an empty list as a default is a classic Python pitfall: the default list is a single mutable object shared across all calls, so modifications persist across invocations, but this does not protect the original list passed as an argument. Option D is wrong because using a global variable as a default introduces shared state and makes the function dependent on external mutable data, which can lead to unintended side effects and violates encapsulation.

36
MCQmedium

Refer to the exhibit. What is the output?

A.Error\nEnd
B.End
C.Error\nOk\nEnd
D.Ok\nEnd
AnswerA

Why this answer

The code attempts to print 'Ok' but raises a TypeError because you cannot concatenate a string and an integer with the + operator. The exception is caught by the bare except clause, which prints 'Error', and then the finally block always executes, printing 'End'. Thus the output is 'Error' followed by 'End' on separate lines.

Exam trap

The PCEP exam often tests the interaction between exception handling and the finally block, specifically that the finally block always executes even when an exception is caught, and that a bare except catches all exceptions, including those from type mismatches.

How to eliminate wrong answers

Option B is wrong because it omits the 'Error' line; the exception is caught and printed before 'End'. Option C is wrong because 'Ok' is never printed due to the TypeError before the print('Ok') line executes. Option D is wrong because it misses both the 'Error' output and incorrectly suggests 'Ok' is printed.

37
Multi-Selectmedium

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

Select 2 answers
A.Tuples are always hashable.
B.Tuples can be used as dictionary keys if all elements are hashable.
C.Tuples do not support indexing.
D.Tuples can only contain immutable objects.
E.Tuples are immutable sequences.
AnswersB, E

A tuple is hashable if all its items are hashable.

Why this answer

Tuples can be used as dictionary keys only when all of their elements are hashable. Since tuples themselves are immutable, their hash value depends on the hash values of their elements; if any element is unhashable (e.g., a list), the tuple itself becomes unhashable and cannot be used as a key.

Exam trap

Python Institute often tests the misconception that 'tuples are immutable' automatically means 'tuples are always hashable' or 'tuples can only contain immutable objects,' leading candidates to incorrectly select options A or D.

38
MCQmedium

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?

A.Use collections.Counter
B.count_dict[word] = count_dict[word] + 1
C.count_dict.setdefault(word, 0); count_dict[word] += 1
D.count_dict[word] = count_dict.get(word, 0) + 1
AnswerD

The get() method returns the current count or 0 if missing, allowing a one-liner update.

Why this answer

`dict.get(word, 0)` returns the current count for `word` (or 0 if missing), then adds 1 and assigns back. This replaces the explicit `if/else` with a single line, making the code more concise and Pythonic while preserving the same logic.

Exam trap

The PCEP exam often tests the distinction between `dict.get()` and direct indexing, trapping candidates who forget that direct access (`dict[key]`) raises `KeyError` for missing keys, while `get()` safely returns a default.

How to eliminate wrong answers

Option A is wrong because `collections.Counter` is a separate class that requires importing and constructing from an iterable; it is not a direct drop-in replacement for the existing dictionary update pattern shown. Option B is wrong because `count_dict[word] = count_dict[word] + 1` raises a `KeyError` if `word` is not already a key in the dictionary. Option C is wrong because `setdefault` returns the existing value (or sets it to 0) but the semicolon-separated statement is less Pythonic; more importantly, the code as written is syntactically incorrect (semicolon instead of newline) and does not use the return value of `setdefault` to avoid the extra lookup.

39
MCQmedium

Refer to the exhibit. What is the output?

A.20 20
B.10 20
C.10 10
D.20 10
AnswerA

Correct. Both prints show 20.

Why this answer

The exhibit shows a function `process` that takes a tuple `data` and converts it to a list, modifies the first element to 20, and returns a tuple of the first two elements. When called with `(10, 20, 30)`, the first call returns `(20, 20)`, so `print(process((10, 20, 30))[0])` prints `20`. The second call does the same, so `print(process((10, 20, 30))[1])` also prints `20`.

Thus, the output is two lines each containing `20`.

Exam trap

The trap here is that candidates often confuse the unpacking of a tuple in a function call with printing the tuple directly, leading them to think the output is a single value or misorder the printed numbers.

How to eliminate wrong answers

Option B is wrong because it suggests the first print outputs `10` and the second `20`, which would occur if the function returned only the first element and the last element was printed separately, but the code as described returns a tuple and unpacks it, so the first print would show both values. Option C is wrong because it outputs `10` and `10`, which would happen if the function returned the same value twice (e.g., `data[0]` twice) or if the tuple was not unpacked correctly, but the code returns `data[0]` and `data[-1]` which are different. Option D is wrong because it outputs `20` and `10`, which would occur if the function returned the last element first and the first element second, but the code returns `data[0]` first and `data[-1]` second.

40
MCQmedium

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?

A.Store the sum and length in global variables
B.Use the tuple as is; Python internally optimizes repeated sum() calls
C.Use a local variable with a simple cache (dictionary) to store sums and lengths for previously seen tuples
D.Convert the tuple to a list and use list operations
AnswerC

Caching avoids redundant computation and keeps the function self-contained.

Why this answer

It implements memoization: a local dictionary caches the sum and length for each tuple key, avoiding repeated computation of sum() and len() for the same static tuple. This reduces time complexity from O(n) per call to O(1) after the first call, without using globals or external libraries, and without changing the function signature.

Exam trap

The PCEP exam often tests the misconception that Python automatically caches results of built-in functions like sum() on repeated calls, when in fact no such optimization exists and the developer must implement caching manually.

How to eliminate wrong answers

Option A is wrong because storing sum and length in global variables would break the requirement to avoid global variables and would not work if multiple different tuples are passed (the cache would be overwritten). Option B is wrong because Python does not internally optimize repeated sum() calls on the same tuple; each call still iterates over the entire tuple, so the performance bottleneck remains. Option D is wrong because converting the tuple to a list adds unnecessary overhead (O(n) conversion) and does not provide any performance benefit over the original tuple for sum() and len().

41
MCQhard

Refer to the exhibit. What is the output?

A.1\n2\n3\nError
B.1\n2\n3\nNone
C.1\n2\n3
D.1\n2\n3\nStopIteration
AnswerD

Why this answer

The code iterates over a tuple (1, 2, 3) using an iterator created by iter(). The for loop internally calls next() on the iterator until StopIteration is raised. After the loop finishes, the final print() statement executes, but since the iterator is exhausted, calling next() again raises StopIteration, which is not caught, so the program terminates with that exception.

Thus, the output is 1, 2, 3 each on a new line, followed by the StopIteration error message.

Exam trap

The trap here is that candidates forget that after a for loop exhausts an iterator, any subsequent manual call to next() on the same iterator will raise StopIteration, not return None or silently fail.

How to eliminate wrong answers

Option A is wrong because it suggests 'Error' as a generic message, but Python specifically raises StopIteration, not a generic error. Option B is wrong because it outputs 'None', but the code does not print None; instead, it raises an unhandled StopIteration exception. Option C is wrong because it omits the exception entirely, but the final print(next(it)) after the loop will raise StopIteration, which is displayed in the output.

42
MCQeasy

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

A.ValueError
B.ZeroDivisionError
C.ArithmeticError
D.TypeError
AnswerB

Correct: Division by zero raises ZeroDivisionError.

Why this answer

The code attempts to divide by zero, which raises a ZeroDivisionError in Python. This is a specific exception for division or modulo operations where the divisor is zero, and it is a subclass of ArithmeticError.

Exam trap

The trap here is that candidates may choose ArithmeticError because it is a parent class, but Python always raises the more specific ZeroDivisionError, and the exam expects you to know the exact exception name.

How to eliminate wrong answers

Option A is wrong because ValueError is raised when a function receives an argument of the correct type but an inappropriate value, not for arithmetic division by zero. Option C is wrong because ArithmeticError is a base class for arithmetic-related exceptions, but Python raises the more specific ZeroDivisionError, not ArithmeticError directly. Option D is wrong because TypeError occurs when an operation or function is applied to an object of inappropriate type, such as dividing a string by an integer, not for dividing by zero.

43
MCQmedium

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?

A.Use the global keyword to refer to the built-in list
B.Use the builtins module (import builtins; builtins.list()) to call the built-in
C.Rename the local variable to something else, like 'lst' or 'data'
D.Remove the local variable and use the input parameter directly
AnswerC

Renaming avoids shadowing the built-in and is the recommended practice.

Why this answer

The best practice is to avoid shadowing built-in names. By renaming the parameter from 'list' to something like 'lst' or 'data', the built-in list() function remains accessible, and the function's external behavior is unchanged. This approach is simple, readable, and follows Python's naming conventions.

Exam trap

The PCEP exam often tests the concept of name shadowing, where candidates mistakenly think that using the 'global' keyword or importing builtins is the proper fix, instead of simply renaming the local variable to avoid shadowing the built-in function.

How to eliminate wrong answers

Option A is wrong because using the 'global' keyword would refer to a global variable named 'list', not the built-in function, and it does not solve the name shadowing issue. Option B is wrong because while importing builtins and calling builtins.list() technically works, it is unnecessarily complex and not considered best practice when a simple rename solves the problem cleanly. Option D is wrong because removing the local variable and using the input parameter directly would change the function's internal logic and potentially break code that relies on the parameter being stored in a variable.

44
Drag & Dropmedium

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

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

Lists are created with brackets, assigned to variables, accessed by index, modified by assignment, and grown with methods.

45
MCQhard

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

A.error2
B.Error: unhandled exception
C.error1
D.ValueError
AnswerA

Correct; the TypeError is raised and caught.

Why this answer

The code raises a `ValueError` inside the `try` block of function `f()`, which is caught by the `except ValueError` handler. That handler then raises a new `TypeError('error2')`. This new exception propagates out of `f()` and is caught by the outer `except TypeError as e` block, which prints the exception message `'error2'`.

Exam trap

The PCEP exam often tests the misconception that the original exception's message or type will be printed, when in fact the `except` block raises a completely new exception that replaces the original.

How to eliminate wrong answers

Option B is wrong because the `TypeError` raised inside the `except ValueError` block is explicitly caught by the outer `except TypeError` handler, so no exception goes unhandled. Option C is wrong because `'error1'` is the message of the original `ValueError`, but that exception is caught and replaced by the `TypeError` before any output occurs. Option D is wrong because the outer `except ValueError` block is never executed — the exception that propagates from `f()` is a `TypeError`, not a `ValueError`.

46
MCQhard

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.distances = {}; for point in points: distances[point] = (point[0]**2 + point[1]**2)
B.distances = {}; for point in points: distances[point] = (point[0]**2 + point[1]**2)**0.5
C.distances = {point: (point[0]**2 + point[1]**2)**0.5 for point in points}
D.distances = {point: point[0]**2 + point[1]**2 for point in points}
E.distances = [(point, (point[0]**2 + point[1]**2)**0.5) for point in points]
AnswerB, C

Technically correct because it computes the Euclidean distance correctly using **0.5 and assigns it to a dictionary with a loop. However, the exam considers option C as the correct answer because it uses a dictionary comprehension, which is more idiomatic and succinct. Therefore, option B is not the intended correct answer.

Why this answer

Options B and C are both correct. Option B uses a for loop to compute the Euclidean distance with the square root and inserts it into a dictionary. Option C achieves the same result with a dictionary comprehension.

Both produce a dictionary mapping each coordinate tuple to its distance from the origin.

Exam trap

Python Institute often tests the distinction between squared distance and actual distance, and between list comprehensions and dictionary comprehensions, to catch candidates who overlook the square root or the correct data structure.

How to eliminate wrong answers

Option A is wrong because it computes the squared distance (sum of squares) instead of the actual distance (square root of sum of squares), so the values are not distances from origin. Option B is wrong because it uses a manual loop and assignment, which is syntactically correct but less Pythonic; however, the primary issue is that it is not the only correct approach, but the question asks 'which code correctly creates the dictionary' and B does create a correct dictionary, but C is more idiomatic and the intended answer; however, strictly speaking B also works, but in PCEP context the comprehension is the expected correct answer. Option D is wrong because it computes the squared distance, not the actual distance.

Option E is wrong because it creates a list of tuples, not a dictionary.

47
MCQhard

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

A.A, B, and C
B.C only
C.B and C
D.A and C
AnswerC

Correct: Outer except catches TypeError, then finally runs.

Why this answer

The inner `try` raises a `TypeError`. The inner `except ValueError` does not catch it, so the exception propagates to the outer `except TypeError`, which catches it and prints 'B'. The `finally` block always executes, printing 'C'.

Thus, the output is 'B' and 'C'.

Exam trap

The PCEP exam often tests the distinction between exception types and the order of `except` blocks, tricking candidates into thinking a `finally` block suppresses exception propagation or that an inner `except` catches unrelated exception types.

How to eliminate wrong answers

Option A is wrong because it suggests 'A' is printed, but the `except ValueError` does not catch a `TypeError`, so 'A' is never printed. Option B is wrong because it claims only 'C' is printed, ignoring that the `TypeError` is caught by the outer `except TypeError`, which prints 'B'. Option D is wrong because it includes 'A', which is never printed, and omits 'B', which is printed.

48
MCQeasy

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?

A.Create a copy of the dictionary at the start: `data = data.copy()`
B.Add the key, then delete it at the end.
C.Modify directly; changes to mutable objects are local only.
D.Convert the dictionary to a tuple before processing.
AnswerA

copy() creates a shallow copy, avoiding modification of original.

Why this answer

Dictionaries are mutable objects in Python, so passing a dictionary to a function passes a reference to the same object. Calling `data.copy()` creates a shallow copy of the dictionary, allowing the function to modify the copy without affecting the original dictionary. This is the standard Pythonic way to avoid side effects on mutable arguments.

Exam trap

Python Institute often tests the misconception that mutable objects are passed by value or that changes inside a function are local, leading candidates to incorrectly choose Option C, which is false for mutable types like dictionaries and lists.

How to eliminate wrong answers

Option B is wrong because adding a key and then deleting it at the end still modifies the original dictionary during execution, which defeats the purpose of avoiding modification; the original dictionary is changed temporarily and may cause issues if an exception occurs before deletion. Option C is wrong because changes to mutable objects like dictionaries are not local — they affect the original object outside the function, as Python passes references to mutable objects, not copies. Option D is wrong because converting a dictionary to a tuple is not possible (tuples are immutable sequences, not mappings) and would raise a TypeError; even if converted, the original dictionary remains unmodified, but the approach is invalid and does not solve the problem.

49
Matchingmedium

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

Why these pairings

These are common string methods used for text manipulation. Correct matches: .upper() converts to uppercase, .lower() to lowercase, .strip() removes leading/trailing whitespace, .split() splits into a list. The distractors swap definitions to test understanding.

50
MCQmedium

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?

A.It returns an empty string.
B.It raises a KeyError.
C.It returns None.
D.It checks the 'in' operator automatically and returns False.
AnswerB

Accessing a non-existent key directly raises KeyError.

Why this answer

In Python, accessing a dictionary key that does not exist raises a KeyError. The dictionary `user` contains only the keys 'id' and 'name', so `user['email']` triggers a KeyError because the key 'email' is not present. This is a fundamental behavior of Python dictionaries, which do not return default values for missing keys unless a method like `.get()` is used.

Exam trap

Python Institute often tests the distinction between direct bracket access (which raises KeyError) and the `.get()` method (which returns None or a default), tempting candidates to think Python automatically returns a falsy value for missing keys.

How to eliminate wrong answers

Option A is wrong because Python dictionaries never return an empty string for a missing key; they raise a KeyError instead. Option C is wrong because `None` is only returned when using the `.get()` method with no default argument, not with direct bracket access. Option D is wrong because the `in` operator is not automatically invoked when accessing a key; it must be explicitly used to check membership, and even then it returns a boolean, not the value.

51
MCQhard

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

A.None
B.Error
C.2
D.1
AnswerC

Correct; finally executes after try's return, and its return value is used.

Why this answer

In Python, a `finally` block always executes, and if both `try` and `finally` contain `return` statements, the `return` in `finally` overrides the one in `try`. The function `test()` returns 2, not 1, because the `finally` block's return value is the one that is actually used.

Exam trap

The PCEP exam often tests the misconception that a `try` block's return will take precedence over a `finally` block's return, leading candidates to pick option D (1) instead of understanding that `finally` overrides the return value.

How to eliminate wrong answers

Option A is wrong because the function does return a value (2), not None. Option B is wrong because no error occurs; the `finally` block executes cleanly and returns a value. Option D is wrong because although `return 1` is executed in the `try` block, the `finally` block's `return 2` overrides it, so the function returns 2, not 1.

52
MCQmedium

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?

A.Use `key, value = line.split('=', 1)` and catch ValueError if less than two parts.
B.Strip the line of whitespace before checking for comments.
C.Check `if '=' not in line: continue` before splitting.
D.Replace `startswith('#')` with `line.lstrip().startswith('#')` and also skip empty lines.
AnswerC

Explicitly skip lines without '='.

Why this answer

The core issue is that lines without an '=' sign (like `#comment`) are still processed by the split, causing the entire line to become a key with no value. By explicitly checking `if '=' not in line: continue` before splitting, the developer ensures that only lines containing a key-value separator are added to the dictionary, effectively filtering out comment lines and any other malformed lines.

Exam trap

Python Institute often tests the misconception that checking for a comment marker alone is sufficient, when the real issue is that any line without an '=' sign (including comments) will be incorrectly parsed as a key with no value.

How to eliminate wrong answers

Option A is wrong because catching a ValueError from `split('=', 1)` would still attempt to split a line like `#comment`, which has no '=', raising the exception; while this would skip the line, it is less explicit and less efficient than checking for '=' beforehand. Option B is wrong because stripping whitespace before checking for comments does not address the root problem: lines without '=' (including comments) will still be split and added to the dictionary. Option D is wrong because while `line.lstrip().startswith('#')` correctly identifies comment lines even with leading whitespace, it does not handle lines that have no '=' sign; such lines would still be processed and added as dictionary entries.

53
Drag & Dropmedium

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

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

In Python, to define a class and create an object, you must first write a class definition using the `class` keyword, which typically includes the `__init__` method (the constructor) to initialize attributes. After that, you instantiate the class by calling it like a function, optionally passing arguments to `__init__`. Finally, you use the resulting object by accessing its attributes or calling its methods.

Any deviation from this order, such as instantiating before defining the class or omitting the constructor, will lead to errors because the class must exist and be properly defined before any objects can be created.

54
MCQmedium

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

A.a = result[0]; b = result[1]
B.(a, b) = result
C.a, b = result
D.a = result[1]; b = result[0]
AnswerB, C

Correct: Parenthesized target list unpacks the tuple into a and b.

Why this answer

Both options B and C correctly unpack the tuple. Option B uses explicit parentheses, while option C uses the implicit form — both are valid tuple unpacking syntax in Python. Option A unpacks via indexing (not tuple unpacking), and option D incorrectly swaps the values.

Exam trap

Candidates may think only one syntactic form is correct, but assignment target lists can be parenthesized or bare; both perform tuple unpacking.

How to eliminate wrong answers

Option D is wrong because it swaps the values: `a = result[1]` assigns the maximum to `a` and `b = result[0]` assigns the minimum to `b`, which does not correctly unpack the tuple as returned by the function (min, max).

55
MCQhard

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?

A.Both in order
B.Neither; program crashes
C.The ValueError except clause
D.The bare except clause
AnswerC

Correct: The specific exception handler is matched first.

Why this answer

When a ValueError is raised in the try block, Python searches the except clauses in the order they appear. It finds the first matching clause, which is `except ValueError:`, and executes it. The bare `except:` clause is only reached if no preceding named except clause matches the exception type.

Exam trap

The PCEP exam often tests the order of except clauses and the fact that Python executes only the first matching handler, leading candidates to mistakenly think both clauses run or that the bare except overrides a specific match.

How to eliminate wrong answers

Option A is wrong because Python executes only the first matching except clause, not both; after handling the ValueError, control passes to the code after the try-except block. Option B is wrong because the ValueError is explicitly caught by the `except ValueError:` clause, so the program does not crash. Option D is wrong because the bare `except:` clause is a catch-all that only runs if no earlier except clause matches the exception; since ValueError matches the first clause, the bare except is skipped.

56
MCQmedium

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?

A.A tuple of lists where each list starts with the key.
B.A dictionary where keys are strings and values are lists.
C.A list of tuples where each tuple contains a key and a list of values.
D.A set of strings representing the keys, with a separate list for values.
AnswerB

Provides O(1) average key lookup and each key maps to a list of allowed values.

Why this answer

A dictionary in Python provides direct key-to-value mapping, making it ideal for storing configuration settings where each string key must map to a list of allowed values. Dictionaries offer O(1) average-time complexity for lookups, which is efficient for retrieving the list of values for a given key. This structure directly models the requirement without unnecessary nesting or indirection.

Exam trap

Python Institute often tests the distinction between data structures that store pairs (like dictionaries) versus those that store sequences (like lists or tuples), and the trap here is that candidates may choose a list of tuples (Option C) because it visually pairs keys and values, but overlook that it lacks the efficient key-based lookup that a dictionary provides.

How to eliminate wrong answers

Option A is wrong because a tuple of lists where each list starts with the key is not a native Python data structure for keyed access; it would require linear scanning to find a key, which is inefficient and error-prone. Option C is wrong because a list of tuples, while able to store key-value pairs, does not provide direct key-based lookup and would require O(n) search time, defeating the purpose of a configuration store. Option D is wrong because using a set of strings for keys with a separate list for values fails to associate each key with its specific list of values, making it impossible to retrieve the correct list for a given key without additional logic.

57
MCQmedium

What is the output of the code in the exhibit?

A.{5:'apple', 6:'banana', 6:'cherry'}
B.{'apple':5, 'banana':7, 'cherry':6}
C.{0:'apple', 1:'banana', 2:'cherry'}
D.{'apple':5, 'banana':6, 'cherry':6}
AnswerD

Correct mapping of items to their lengths.

Why this answer

The code creates a dictionary using the `dict()` constructor with a list of tuples. Each tuple is a key-value pair. The keys are strings ('apple', 'banana', 'cherry') and the values are integers (5, 6, 6).

The resulting dictionary is {'apple':5, 'banana':6, 'cherry':6}.

Exam trap

The PCEP exam often tests the distinction between `dict()` with a list of tuples versus other dictionary creation methods, and the trap here is that candidates mistakenly think the tuples are reversed or that keys are auto-generated as indices.

How to eliminate wrong answers

Option A is wrong because it shows integer keys (5, 6, 6) with string values, which reverses the order of the tuples. Option B is wrong because it assigns value 7 to 'banana', but the second tuple is ('banana',6), not ('banana',7). Option C is wrong because it shows auto-generated integer keys (0,1,2) with string values, which would only happen if the input were a sequence of values without explicit keys, not a list of key-value tuples.

58
MCQhard

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

A.lambda a, b: a + b
B.lambda a, b: a - b
C.lambda a, b: return a + b
D.def add(a, b): return a + b
AnswerA

Correct. The expression 'lambda a, b: a + b' is a valid lambda function that sums two arguments.

Why this answer

Option A correctly defines a lambda function that takes two arguments and returns their sum. Option B is a valid lambda but returns the difference (a - b), not the sum, so it does not meet the requirement. Option C is incorrect because lambda expressions cannot include a `return` statement; the result is implicitly returned.

Option D uses `def` to define a named function, not a lambda.

Exam trap

Python Institute often tests the misconception that lambda requires an explicit `return` statement, leading candidates to choose Option C, but in reality the expression after the colon is automatically returned.

How to eliminate wrong answers

Option B is wrong because it is syntactically identical to Option A, but the question asks for 'which of the following lambda expressions is correct' and only one answer is marked as correct; in this context, Option B is a duplicate and not the intended correct choice. Option C is wrong because it uses `return` inside a lambda, which is invalid syntax — lambda bodies can only contain a single expression, not a statement like `return`. Option D is wrong because it is a regular function definition using `def`, not a lambda expression, so it does not meet the requirement of being a lambda.

59
MCQhard

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

A.15 15
B.13 15
C.15 13
D.8 8
AnswerC

Why this answer

The code defines a function `func` that attempts to modify a tuple element (`t[1] = 10`). Since tuples are immutable, this raises a `TypeError`. The `except` block catches the error and prints `x` (15) followed by `t[1]` (13), resulting in the output '15 13'.

Therefore, the correct answer is C.

Exam trap

Candidates may overlook tuple immutability and mistakenly assume the modification succeeds. Additionally, the order of printed values (x first, then t[1]) can cause confusion if the exhibit's print statement is not carefully read.

How to eliminate wrong answers

Option A is wrong because it assumes the tuple modification succeeds and prints 15 15, but tuples are immutable so a TypeError occurs. Option B is wrong because it prints 13 15, which would be correct if the print order were `t[1]` then `x`, but the exhibit's print order (based on the correct answer) is `x` then `t[1]`. Option D is wrong because it prints 8 8, which would only happen if the function were called with different arguments or if the tuple were modified to 8, which is impossible due to immutability.

60
MCQhard

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

A.0 1 2
B.0 0 0
C.2 2 2
D.3 3 3
AnswerC

Correct: i is 2 at the end of the loop, so all functions return 2.

Why this answer

The code defines a tuple `t = (0, 1, 2)`. The `for` loop iterates over the tuple, but each iteration prints `t[2]`, which is the third element (index 2) with value 2. Since the value is constant, it prints '2' three times.

Hence the output is '2 2 2'.

Exam trap

The trap is that candidates might assume the loop prints each element of the tuple (0, 1, 2) sequentially, but the code prints the element at index 2 (the third element) each time, resulting in three copies of 2.

How to eliminate wrong answers

Option A is wrong because it assumes the loop prints the current element `x` (0, 1, 2) rather than the fixed index `t[0]`. Option B is wrong because it assumes `t[0]` changes during iteration or that the tuple is modified, but tuples are immutable and `t[0]` remains `2`. Option D is wrong because it assumes the loop runs three times and prints `t[0]` but mistakenly thinks `t[0]` is `3`, which is not an element of the tuple.

61
Multi-Selectmedium

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

Select 2 answers
A.(1)
B.[1, 2]
C.int(1)
D.tuple([1, 2])
E.(1, 2)
AnswersD, E

Correct; converts list to tuple.

Why this answer

`tuple([1, 2])` calls the `tuple()` constructor with a list `[1, 2]` as an argument, which converts the list into a tuple `(1, 2)`. Option E is correct because `(1, 2)` is the literal syntax for a tuple containing the elements 1 and 2.

Exam trap

Python Institute often tests the misconception that parentheses alone create a tuple, leading candidates to select `(1)` as a valid tuple, when in fact a trailing comma is required for a single-element tuple (e.g., `(1,)`).

62
Multi-Selectmedium

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

Select 2 answers
A.d = {'a': 1, 'b': 2}
B.d = ('a'=1, 'b'=2)
C.d = dict.fromkeys(['a', 'b', 'c']) # without value
D.d = dict(a=1, b=2)
E.d = dict(['a', 'b'], [1, 2])
AnswersA, D

Standard dictionary literal.

Why this answer

It uses the standard literal syntax for creating a dictionary with initial key-value pairs. The curly braces `{}` with colon-separated keys and values are the most common and direct way to define a dictionary in Python.

Exam trap

Python Institute often tests the distinction between the literal `{}` syntax and the `dict()` constructor, and candidates may mistakenly think that `dict()` can accept two separate lists as positional arguments, similar to how `zip()` works, or that parentheses can be used to define a dictionary.

63
MCQmedium

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?

A.[1] and [1]
B.[1] and [1,1]
C.TypeError
D.[1] and [2]
AnswerB

Correct: The default list is created once and appended to each call.

Why this answer

The default argument `my_list=[]` is evaluated only once at function definition time, not each time the function is called. Therefore, the first call `add_item(1)` appends 1 to the same list object, returning `[1]`. The second call appends another 1 to that same list, returning `[1, 1]`.

This is a classic Python gotcha involving mutable default arguments.

Exam trap

The PCEP exam often tests the mutable default argument trap — the trap here is that candidates mistakenly believe default arguments are re-evaluated on every function call, leading them to choose option A, when in fact they are evaluated only once at definition time.

How to eliminate wrong answers

Option A is wrong because it assumes the default list is recreated on each call, which is not how Python handles mutable default arguments — the list persists across calls. Option C is wrong because no TypeError occurs; the function is called correctly with a single positional argument, and the default list handles the missing second argument. Option D is wrong because it suggests the second call returns `[2]`, which would require the item argument to be 2 or some other mutation, but the same integer 1 is appended both times.

64
MCQhard

Refer to the exhibit. What is the output?

A.[1]\n[2]\n[3]
B.[1]\n[2]\n[1, 3]
C.[1]\n[2]\n[1,2,3]
D.[1]\n[2]\n[1]
AnswerB

Why this answer

The code defines a function `func` that takes a list as a parameter and modifies it by appending the value 3. The list `lst` is initially `[1]`. After calling `func(lst)`, the list becomes `[1, 3]`.

The output prints the list at three stages: before the call (`[1]`), inside the function (`[2]`), and after the call (`[1, 3]`). Option B correctly shows these three lines.

Exam trap

Python Institute exams often test the misconception that function parameters create a copy of the list, leading candidates to think the original list remains unchanged, but in reality, mutable objects like lists are passed by reference and modifications affect the original.

How to eliminate wrong answers

Option A is wrong because it shows `[1]`, `[2]`, `[3]`, which incorrectly implies the list after the function call is `[3]` instead of `[1, 3]`. Option C is wrong because it shows `[1]`, `[2]`, `[1,2,3]`, which incorrectly adds 2 to the list, but the function only appends 3, not 2. Option D is wrong because it shows `[1]`, `[2]`, `[1]`, which incorrectly suggests the list is unchanged after the function call, ignoring the append operation.

65
MCQmedium

What is the output of the code?

A.None
B.inf
C.2.0
D.An unhandled ZeroDivisionError is raised.
AnswerD

Correct. Although the option states 'TypeError', the actual exception is ZeroDivisionError, but the key point is that an unhandled exception is raised, terminating the program.

Why this answer

The code divides by zero, which raises a ZeroDivisionError. The try-except block does not catch ZeroDivisionError (it catches a different exception or does not have an appropriate except clause), so the exception is unhandled, causing the program to terminate with a traceback. The output is not None; an unhandled exception is raised.

Exam trap

Candidates may assume the ZeroDivisionError is caught by the try-except block, but it is not; the exception goes unhandled, terminating the program.

How to eliminate wrong answers

Option B is wrong because 'inf' is not a valid output in Python for division by zero; Python raises a ZeroDivisionError, not returning infinity. Option C is wrong because 2.0 would only result from a valid division like 2 / 1, not from 2 / 0. Option D is wrong because the error raised is a ZeroDivisionError, not a TypeError; TypeError occurs for operations between incompatible types, not for arithmetic division by zero.

66
MCQeasy

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?

A.The tuple is updated to ("Jan","Februar","Mar")
B.A ValueError is raised
C.An AttributeError is raised
D.A TypeError is raised
AnswerD

Correct: Tuples do not support item assignment, so TypeError is raised.

Why this answer

Tuples in Python are immutable, meaning their elements cannot be changed after creation. Attempting to assign a new value to an index of a tuple (e.g., months[1] = "Februar") raises a TypeError, not a ValueError or AttributeError. This is because the assignment operation is not supported for tuple objects.

Exam trap

The PCEP exam often tests the distinction between mutable (list) and immutable (tuple) types, and the trap here is that candidates confuse the immutability error with a ValueError or AttributeError, or assume tuples can be modified like lists.

How to eliminate wrong answers

Option A is wrong because tuples are immutable, so the assignment fails and the tuple remains unchanged; it is not updated. Option B is wrong because a ValueError is raised for operations like unpacking with wrong number of values or invalid literal conversion, not for attempting to modify an immutable object. Option C is wrong because an AttributeError occurs when accessing a method or attribute that does not exist on an object (e.g., months.append()), not when performing an assignment to an index.

67
Multi-Selecteasy

Which THREE of the following are characteristics of Python tuples?

Select 3 answers
A.They are hashable
B.They are ordered
C.They are mutable
D.They support item assignment
E.They can contain duplicate values
AnswersA, B, E

Tuples are hashable if all their elements are hashable, allowing them to be used as dictionary keys.

Why this answer

Tuples are immutable sequences, and immutability is a key requirement for an object to be hashable in Python. A hashable object must have a hash value that never changes during its lifetime, which allows it to be used as a dictionary key or set member. Since tuples cannot be modified after creation, they satisfy this requirement, provided all their elements are also hashable.

Exam trap

The PCEP exam often tests the distinction between mutable and immutable types by pairing 'ordered' and 'hashable' as correct for tuples, while candidates mistakenly think tuples support item assignment or are mutable because they confuse them with lists.

68
MCQeasy

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?

A.Use config.get(key, 'N/A') instead of direct key access
B.Wrap each access in a try-except block to catch KeyError and assign 'N/A'
C.Use if key in config: value = config[key] else: value = 'N/A'
D.Use config.setdefault(key, 'N/A') before accessing
AnswerA

The get() method returns the specified default if key is missing, avoiding exceptions.

Why this answer

`dict.get(key, default)` is the idiomatic Python method for safely retrieving a value from a dictionary without raising a `KeyError`. It returns the default value `'N/A'` when the key is missing, which directly solves the crash while keeping the code concise and readable. This approach is more efficient than exception handling or explicit membership checks because it performs a single hash lookup.

Exam trap

The PCEP exam often tests the distinction between `dict.get()` and `dict.setdefault()`, trapping candidates who think `setdefault()` is a safe retrieval method without realizing it permanently modifies the dictionary by adding the missing key.

How to eliminate wrong answers

Option B is wrong because wrapping each access in a try-except block is verbose, less readable, and slower than using `.get()` due to the overhead of exception handling; it also violates Python's EAFP (Easier to Ask for Forgiveness than Permission) principle in a case where a simple method exists. Option C is wrong because using `if key in config:` performs two dictionary lookups (one for the membership test and one for the retrieval), which is less efficient and more verbose than the single lookup in `.get()`. Option D is wrong because `config.setdefault(key, 'N/A')` modifies the dictionary by inserting the key with the default value if it is missing, which is not the intended behavior—the script should only retrieve a value or return 'N/A' without altering the original dictionary.

69
Multi-Selecthard

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

Select 3 answers
A.Using a `try` block with both `except` and `finally` blocks.
B.Using a `finally` block without a `try` block.
C.Using a `try` block with an `else` block but no `except` block.
D.Using a `try` block with a `finally` block.
E.Using a `try` block with one or more `except` blocks.
AnswersA, D, E

Combination is valid.

Why this answer

Python's exception handling allows a `try` block to be followed by both `except` and `finally` blocks. The `except` block catches specific exceptions, while the `finally` block always executes (for cleanup), regardless of whether an exception occurred. This combination is fully valid and commonly used for robust resource management.

Exam trap

Python Institute often tests the rule that an `else` block cannot exist without at least one `except` block, and that a `finally` block must always be attached to a `try` block, leading candidates to mistakenly think these standalone constructs are valid.

70
MCQeasy

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

A.The program crashes
B.Invalid
C.(Nothing printed)
D.abc
AnswerB

The ValueError is raised and caught, printing 'Invalid'.

Why this answer

The code attempts to convert the string 'abc' to an integer using int(). Since 'abc' is not a valid integer, Python raises a ValueError. The except block catches this specific exception and executes print('Invalid'), so the output is 'Invalid'.

Option B is correct because the exception is handled gracefully without crashing.

Exam trap

The PCEP exam often tests whether candidates understand that a caught exception does not crash the program; the trap here is that some candidates think any error causes a crash, but the except block prevents that.

How to eliminate wrong answers

Option A is wrong because the ValueError is explicitly caught by the except block, preventing the program from crashing; unhandled exceptions cause crashes, but here the exception is handled. Option C is wrong because the except block executes and prints 'Invalid', so something is printed. Option D is wrong because the code does not print the original string 'abc'; it prints the string 'Invalid' from the except block.

71
MCQmedium

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

A.sorted(lst, key=len, reverse=True)
B.sorted(lst, reverse=True)
C.sorted(lst, key=lambda s: len(s), reverse=True)
D.sorted(lst, key=lambda s: len(s))
AnswerA

Correct: Uses `key=len` to sort by length and `reverse=True` for descending order.

Why this answer

Option A is correct. `sorted(lst, key=len, reverse=True)` sorts the list by string length in descending order. Although option C (`sorted(lst, key=lambda s: len(s), reverse=True)`) would also produce the same result, this single-answer question expects the most straightforward and Pythonic solution, which is using the built-in `len` function directly without an unnecessary lambda. Option B sorts alphabetically in reverse order, not by length.

Option D sorts by length in ascending order.

Exam trap

A common trap is assuming `reverse=True` alone sorts by length; it actually sorts alphabetically. Another trap is thinking a lambda is required when the built-in `len` works directly as the key.

How to eliminate wrong answers

Option A is wrong because `key=len` sorts by length but without a lambda, though it would work if `reverse=True` were present; however, the question specifically expects the lambda form as the correct answer in this PCEP context. Option B is wrong because `reverse=True` alone sorts strings in reverse alphabetical order, not by length. Option D is wrong because it sorts by length in ascending order (the default), not descending.

72
MCQeasy

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

A.0
B.None
C.KeyError
D.1
AnswerA

Correct; get returns the default 0.

Why this answer

The `get()` method on a dictionary returns the value for the given key if it exists; otherwise, it returns the default value provided as the second argument. Since key `'b'` is not in dictionary `d`, the method returns `0` (the specified default). Option A is correct because `d.get('b', 0)` explicitly supplies a default of `0`.

Exam trap

The PCEP exam often tests the distinction between `dict.get()` (which returns a default or `None`) and direct subscript access `d[key]` (which raises `KeyError`), trapping candidates who confuse the two behaviors.

How to eliminate wrong answers

Option B is wrong because `get()` returns `None` only when no default is provided and the key is missing; here a default of `0` is given. Option C is wrong because `get()` never raises a `KeyError` — that would occur with direct indexing like `d['b']`. Option D is wrong because `1` is the value for key `'a'`, not for key `'b'`.

73
MCQeasy

Refer to the exhibit. What type of exception occurred?

A.ZeroDivisionError
B.TypeError
C.ValueError
D.ArithmeticError
AnswerA

Correct; as shown in the traceback.

Why this answer

The code attempts to divide by zero (e.g., `10 / 0`), which raises a `ZeroDivisionError` in Python. This is a specific built-in exception for division or modulo operations where the divisor is zero.

Exam trap

The PCEP exam often tests the distinction between the generic `ArithmeticError` and its specific subclass `ZeroDivisionError`, trapping candidates who think the parent class is raised directly instead of the more specific exception.

How to eliminate wrong answers

Option B is wrong because `TypeError` occurs when an operation or function is applied to an object of inappropriate type, not when dividing by zero. Option C is wrong because `ValueError` occurs when a function receives an argument with the right type but an inappropriate value (e.g., `int('abc')`), not for division by zero. Option D is wrong because `ArithmeticError` is a base class for arithmetic-related exceptions, but Python raises the more specific `ZeroDivisionError` (a subclass of `ArithmeticError`) for division by zero, not the parent class directly.

74
Multi-Selecteasy

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

Select 2 answers
A..pop()
B..index()
C..append()
D..sort()
E..count()
AnswersB, E

index returns first index of a value.

Why this answer

The `.index()` method is a built-in tuple method that returns the index of the first occurrence of a specified value. Tuples are immutable sequences, so they support only non-mutating methods like `.index()` and `.count()`, which do not modify the tuple.

Exam trap

The PCEP exam often tests the distinction between mutable and immutable sequence types, trapping candidates who assume that because lists have methods like `.pop()`, `.append()`, and `.sort()`, tuples must have them too, when in fact tuples only support non-mutating methods like `.index()` and `.count()`.

75
MCQmedium

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

A.t[-1]
B.t[5]
C.t[4]
D.t[0]
AnswerA

Negative index -1 refers to the last element.

Why this answer

In Python, negative indices count from the end of a sequence. For the tuple t = (1, 2, 3, 4, 5), t[-1] accesses the last element (5), because -1 refers to the final position. This is a standard feature of Python's sequence indexing.

Exam trap

A common trap in PCEP exams is that candidates may use a hardcoded index like t[4] which works for this specific tuple but fails if the tuple length changes. The correct dynamic way is t[-1], which always references the last element regardless of tuple length.

How to eliminate wrong answers

Option B is wrong because t[5] attempts to access index 5, which is out of range for a tuple with indices 0 through 4, raising an IndexError. Option C is wrong because t[4] returns the element at index 4, which is 5, but this is the last element only coincidentally; the question asks for an expression that returns the last element in general, and t[4] is not a robust way to do it if the tuple length changes. Option D is wrong because t[0] returns the first element (1), not the last.

Page 1 of 2 · 82 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Functions, Tuples, Dictionaries and Exceptions questions.