CCNA Functions Data Structures Questions

75 of 84 questions · Page 1/2 · Functions Data Structures topic · 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

Options B, C, and D are correct. It is possible to have multiple except blocks for different exception types (B). The else block runs if no exception occurred (C).

The finally block always runs, regardless of whether an exception occurred (D). Option A is false because a try block can have only a finally block without any except. Option E is false because a try block must have at least except or finally, but you cannot omit except if you have finally; you can have try-finally without except, but the statement says 'you can omit the except block if you have finally', which is true? Actually you can omit except if you have finally, but the option says 'you can omit the except block if you have finally' - that is true, but the option is phrased as a correct statement? Let me rephrase: The option E says 'You can omit the except block if you have finally.' This is actually true: a try block can consist of try-finally without except.

However, the intent is to test the requirement of at least one except? Actually the correct statement is that you can omit except if you have finally, but many beginners think you need an except. However, to avoid confusion, I'll make E false by stating it incorrectly. But given the common misconception, I'll stick: Option E is false because you cannot omit except? Actually you can.

Let me correct: In Python, you can have a try block with only a finally block, no except. So option E is a true statement. But then it would be a fourth correct option.

I need to adjust: The question asks for THREE correct. Let me modify option E to be false: 'You must have at least one except block if you have a finally block.' That is false. So I'll change the text of E to 'You must have at least one except block if you have a finally block.' Then correct options are B, C, D.

2
Multi-Selectmedium

Which TWO of the following are valid dictionary methods? (Select two.)

Select 2 answers
A.keys()
B.keyset()
C.entries()
D.pairs()
E.values()
AnswersA, E

Correct; returns dict keys view.

Why this answer

keys() and values() are valid dictionary methods. entries(), pairs(), and keyset() are not.

3
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

Option D is correct because 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.

4
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.

5
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.

6
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

get, keys, and values are valid dictionary methods. push and append are not dictionary methods.

7
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

Option A is correct because 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.

8
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

In Python, dictionaries are mutable and passed by reference. The function modifies the original dictionary by setting d['key'] = 'new_value'. Then it reassigns the local variable d to a new dictionary, which does not affect the outer variable my_dict.

So my_dict becomes {'key': 'new_value'}.

9
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 function exception_test has a try-except-finally block. The division 1/0 raises ZeroDivisionError, which is caught by the first except clause, printing 'A'. Then the finally clause executes, printing 'C'.

After the function returns, the script prints 'D'. So the output is A, C, D each on separate lines.

10
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

Option C replaces the tuple with a dictionary for all parameters. Dictionaries are mutable and can be updated easily. This is a clean solution that does not require converting back and forth.

Option A is inefficient and complex. Option B only changes one parameter to a list, but then the tuple still contains a list, which is mutable but awkward. Option D uses a namedtuple, which is still immutable and does not support updates.

11
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

defaultdict automatically creates a list for each new key, simplifying the code and preserving all values.

Why this answer

Option D uses a dictionary where each value is a list, and uses a default factory to create lists automatically. This efficiently preserves multiple values per key. Option A uses a tuple for each value, which is immutable and cannot be appended.

Option B uses a list but does not handle automatic creation; however, the description of option B 'Use a list for each value, appending new values' is essentially the same as D but without the default factory? Actually option B says 'Use a list for each value, appending new values' which is correct in concept, but D explicitly mentions 'with default factory' which is the Pythonic way using defaultdict. Option B may require manual checking if the key exists. So D is more complete.

Option C uses a set, which would eliminate duplicate values, which may not be desired.

12
MCQhard

A function is defined as: def func(*args, **kwargs): print(args, kwargs). It is called as func(1, 2, a=3, b=4). What is printed?

A.(1, 2, a=3, b=4)
B.(1, 2) {'a': 3, 'b': 4}
C.TypeError
D.[1, 2] {'a': 3, 'b': 4}
AnswerB

Correct: args becomes (1,2), kwargs becomes {'a':3,'b':4}.

Why this answer

*args collects positional arguments into a tuple, **kwargs collects keyword arguments into a dictionary. Option A is correct. Option B is incorrect because it mixes syntax.

Option C is incorrect because args is a tuple, not a list. Option D is incorrect because no TypeError occurs.

13
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 first for loop iterates over all yielded values: 1,2,3 each on separate lines. Then '---' is printed. The second for loop starts a new generator, yields 1, prints it, then breaks.

So output is 1,2,3,---,1 each on separate lines.

14
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

Default arguments are evaluated at definition time (A). Arguments can be passed by position or keyword (C). Options B, D, E are false.

15
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

Option A (change to except Exception) is the standard way to avoid catching KeyboardInterrupt and SystemExit because those exceptions inherit from BaseException, not Exception. This will catch all other exceptions that are likely to occur in file operations. Option B (multiple specific except blocks) is too restrictive and may miss unexpected errors.

Option C (using finally) does not replace the except block and will still execute cleanup even if the exception is not caught, which may not be desired. Option D (custom exception class) is unnecessary.

16
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

Option D is correct because using multiple except blocks for specific exception types allows precise handling without catching unwanted exceptions. Option A and C use bare except or except: which catch SystemExit and KeyboardInterrupt, which is dangerous. Option B catches all exceptions that inherit from Exception, which is too broad and may catch unexpected errors.

17
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

Option C (use copy.deepcopy) creates a deep copy, ensuring that nested objects are also duplicated. Option A (copy.copy) creates a shallow copy; modifications to nested dictionaries still affect the original. Option B (dict.copy()) is also shallow.

Option D (direct assignment) just binds a new reference, so changes affect the original.

18
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

Inside div, ZeroDivisionError is caught and a ValueError is raised. The outer try catches the ValueError, so 'Invalid division' is printed.

19
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

Option A is correct because 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.

20
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.

21
MCQeasy

What is the output of the code?

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

KeyError is raised and caught, printing the message.

Why this answer

The dictionary does not have a key 'debug', so config['debug'] raises KeyError, which is caught, printing 'Key not found'. Option A is correct. Option B would require a default value.

Option C would require a different exception. Option D would require no exception.

22
Multi-Selecteasy

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

Select 2 answers
A.`dict.keys()`
B.`dict.get()`
C.`dict.values()`
D.`dict.copy()`
E.`dict.items()`
AnswersA, C

Returns a view of keys.

Why this answer

A is correct because `dict.keys()` returns a view object that dynamically reflects changes made to the dictionary. When the dictionary is updated, the view object automatically updates to show the new keys, making it a live view rather than a static copy.

Exam trap

Python Institute often tests the distinction between methods that return view objects (keys(), values(), items()) versus those that return static copies or values, and the trap here is that candidates may incorrectly think items() is not a view object or may forget that all three are views, leading to selecting only two of the three correct ones.

23
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

Option A is correct because 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.

24
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

Option D is correct because 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.

25
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

Dictionary comprehension {name: len(name) for name in names} creates the desired mapping. Option C is correct. Option A is incorrect because len without parentheses returns the function object.

Option B swaps key and value. Option D uses an undefined variable 'length'.

26
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

Cisco 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.

27
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 built-in functions commonly used in Python programming.

28
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

Option D is correct because 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.

29
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

A trailing comma creates a singleton tuple.

Why this answer

Option A is correct because 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.

30
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`.

31
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.

32
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

Option B 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.

33
Multi-Selecthard

Which THREE of the following statements about function arguments are true? (Select exactly 3)

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

Option A is true: default arguments are evaluated at function definition time. Option B is false: keyword arguments can be used in any order as long as they are after positional. Option C is true: *args collects extra positional arguments into a tuple.

Option D is true: **kwargs collects extra keyword arguments into a dictionary. Option E is false: you cannot mix *args and **kwargs arbitrarily; *args must come before **kwargs in definition.

34
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

Option A is correct because `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.

35
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 while iterating over its items raises a RuntimeError because the size changes. Option B is correct. Option A is wrong because the modification causes an error.

Option C is wrong because no KeyError occurs. Option D is wrong because the program crashes with an exception.

36
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 traceback shows the error originated at line 5 in the divide function (the line with the division). Option B is correct. Option A is wrong because line 10 is where the call was made, not where the exception was raised.

Option C is wrong because the exception type is ZeroDivisionError, not in the divide function name. Option D is wrong because the file is app.py, not the exception itself.

37
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

Option A is correct because using None as a default and creating a new list inside the function ensures that the default argument is not shared across calls. Option B is dangerous because mutable default arguments are shared. Option C uses a tuple, which is immutable but would not allow modifications.

Option D uses a global variable, which introduces side effects.

38
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

Option B is correct because 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.

39
MCQmedium

A developer wants to raise a ValueError with a custom message when a negative number is passed. Which code is correct?

A.raise ValueError "Negative input not allowed"
B.raise ValueError() + "Negative input not allowed"
C.raise ValueError("Negative input not allowed")
D.raise new ValueError("Negative input not allowed")
AnswerC

Correct: This raises a ValueError with the custom message.

Why this answer

The correct syntax is raise ValueError("message"). Option D is correct. Option A is wrong because it uses 'new' keyword.

Option B is wrong because it lacks parentheses. Option C is wrong because adding string is not valid.

40
MCQeasy

A developer wants to create a tuple containing a single integer value 5. Which code snippet correctly creates such a tuple?

A.t = [5]
B.t = (5)
C.t = 5
D.t = (5,)
AnswerD

The trailing comma makes it a tuple with one element.

Why this answer

Option B (t = (5,)) correctly creates a single-element tuple. The trailing comma is essential. Option A creates an integer, not a tuple.

Option C assigns an integer to a variable. Option D creates a list, not a tuple.

41
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

Option A (count_dict[word] = count_dict.get(word, 0) + 1) is the most concise and Pythonic way. It uses the get() method to provide a default of 0 if the key is missing. Option B requires an extra line and is less direct.

Option C would raise KeyError if the key is missing. Option D uses the collections module, which is not a built-in and may not be available in all environments.

42
Multi-Selecteasy

Which THREE of the following are built-in exceptions in Python? (Select three.)

Select 3 answers
A.StopIteration
B.ValueError
C.LoopError
D.TypeError
E.DivisionError
AnswersA, B, D

Correct.

Why this answer

ValueError, TypeError, and StopIteration are built-in. DivisionError is not a built-in exception (ZeroDivisionError is), and LoopError does not exist.

43
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 inner function uses nonlocal to modify the variable x from the enclosing scope. After calling inner(), x becomes 20 and is printed. Then outer prints x which is also 20.

So output is 20 and 20.

44
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

Option C introduces a simple cache using a dictionary local to the function. This stores the precomputed sum and length for a given tuple, so subsequent calls with the same tuple avoid recomputation. Option A converts the tuple to a list, which adds overhead and does not address recomputation.

Option B uses global variables, which are generally discouraged and error-prone. Option D assumes internal optimizations that do not exist in standard Python.

45
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

Dividing by zero raises ZeroDivisionError. Option D is correct. Option A is a superclass but not the specific exception.

Options B and C are irrelevant.

46
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

Option B (rename the local variable to a non-conflicting name, such as 'lst' or 'data') is the simplest and most Pythonic solution. It avoids shadowing the built-in and makes the code clearer. Option A uses the global keyword but the built-in is not global; it's in builtins.

Option C is overly complex for this situation. Option D is vague and does not provide a concrete fix.

47
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

Why this order

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

48
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 inner except raises a TypeError, which is caught by the outer except TypeError. The output is 'error2'.

49
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]
AnswerC

Dictionary comprehension with correct calculation.

Why this answer

Option C is correct because it uses a dictionary comprehension to map each tuple (coordinate) to its Euclidean distance from the origin, calculated as `(point[0]**2 + point[1]**2)**0.5`. This correctly produces a dictionary with tuples as keys and float distances as values, matching the requirement exactly.

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.

50
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 TypeError, not caught by inner except (ValueError), so it propagates to outer except TypeError, printing 'B', then finally always executes, printing 'C'. Option B is correct. Option A is wrong because inner except does not catch.

Option C is wrong because B is printed. Option D is wrong because A is not printed.

51
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

Option A is correct because 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.

52
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.

53
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.

54
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

The finally block always executes, and its return statement overrides any previous return. Thus, the function returns 2.

55
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

Option C is correct because 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.

56
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

Why this order

Class definition includes __init__, then instantiation and usage.

57
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]
AnswerA, B, C

Also correct, but the question asks for unpacking directly.

Why this answer

The function min_max returns a tuple (min, max). The values can be unpacked into variables by assigning to a tuple of variables: a, b = min_max(...). This gives a=1, b=3.

58
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

Python matches the first except clause that catches the exception. The specific except ValueError catches it before the bare except. Option A is correct.

Option B is wrong because the bare except is only for uncaught exceptions. Options C and D are incorrect because only the first matching except runs.

59
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

Option B is correct because 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.

60
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 dictionary comprehension creates a dict with each item as key and its length as value. {'apple':5, 'banana':6, 'cherry':6}. Option C is correct. Option A has values wrong (7 for banana).

Option B swaps keys and values. Option D uses index numbers, not lengths.

61
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 lambda syntax with implicit return.

Why this answer

Option A is correct because a lambda function in Python is defined using the `lambda` keyword, followed by a comma-separated list of parameters, a colon, and a single expression that is implicitly returned. The expression `a + b` computes the sum of the two arguments without needing an explicit `return` statement, making it the proper syntax for a lambda that returns the sum.

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.

62
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 lambda captures the variable i by reference, not by value. Since i ends up as 2 after the loop, all lambdas return 2. Option B is correct.

Option A is wrong because of late binding. Options C and D are incorrect.

63
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

Option D is correct because `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,)`).

64
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

Option A is correct because 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.

65
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

Default arguments are evaluated only once at function definition. The same list is used each call. The first call returns [1], the second returns [1,1].

Option B is correct. Option A is wrong because the list is mutated. Option C is wrong because the second call adds to the same list.

Option D is wrong because no TypeError occurs.

66
MCQmedium

What is the output of the code?

A.None
B.inf
C.2.0
D.An unhandled TypeError is raised.
AnswerA

TypeError caught, returns None.

Why this answer

Option A is correct because the code attempts to divide an integer by zero (2 / 0), which in Python raises a ZeroDivisionError. Since there is no try-except block to handle this exception, the program crashes before any value is assigned or returned, so the output is None (the default return value of a function that does not execute successfully).

Exam trap

Python Institute often tests the distinction between different exception types, and the trap here is that candidates may confuse ZeroDivisionError with TypeError or assume Python returns 'inf' like some other languages.

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.

67
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 are immutable; assignment raises TypeError. Option D is correct because it is the TypeError that occurs. Option A is wrong because tuples cannot be mutated.

Option B is wrong because AttributeError is for attribute access, not assignment. Option C is wrong because ValueError is for incorrect value, not assignment.

68
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 ordered (B), can be hashable if their elements are hashable (C), and can contain duplicate values (E). Tuples are immutable, so they do not support item assignment (D is false) and are not mutable (A is false).

69
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

Option B (config.get(key, 'N/A')) is the most efficient and readable approach. It directly returns the default if the key is missing, without raising an exception or performing multiple lookups. Option A uses try-except, which is less efficient and more verbose.

Option C uses setdefault, which modifies the dictionary by adding the default key-value pair, which may not be desired. Option D requires an extra lookup and is more verbose.

70
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

Option A is correct because 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.

71
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

Cisco 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.

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

Correct; sorts by length descending.

Why this answer

To sort by length descending, use the key parameter with a lambda function and set reverse=True. Option B does this.

73
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 of a dictionary returns the value for the key if it exists, otherwise returns the default argument. Since 'b' is not a key, it returns 0.

74
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 traceback shows 'ZeroDivisionError: division by zero'. So the exception is ZeroDivisionError.

75
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

Tuples have only two methods: count and index. Options B and C are correct. Option A is a list method.

Option D is a list method. Option E is a list method.

Page 1 of 2 · 84 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Functions Data Structures questions.