Courseiva

Certified Entry-Level Python Programmer PCEP (PCEP) — Questions 226300

498 questions total · 7pages · All types, answers revealed

Page 3

Page 4 of 7

Page 5
226
MCQhard

A data analyst uses Python to process a CSV file containing sales data. The file has columns: 'Product', 'Price', 'Quantity'. The analyst writes a script to compute total sales: sum of Price * Quantity for each row. The code reads each row as a list of strings. The analyst uses: total = 0; for row in reader: total += row['Price'] * row['Quantity']; print(total). The script raises a TypeError. What is the best fix?

A.Convert Price and Quantity to float before multiplication.
B.Change the loop to for i in range(len(reader)): total += reader[i][1] * reader[i][2].
C.Use integer multiplication and then convert to float.
D.Use float(row[1]) * float(row[2]) instead of row['Price'] * row['Quantity'].
AnswerD

Correct: uses integer indices to access list elements and performs float conversion, resolving both the key error and the string multiplication error.

Why this answer

The TypeError occurs because row is a list of strings, so integer indices must be used instead of string keys. Multiplying strings also requires conversion. Option D correctly uses float(row[1]) * float(row[2]) with indices, fixing both issues.

Option A only converts to float but still uses invalid string keys.

Exam trap

Python Institute often tests the distinction between string repetition (valid) and string multiplication of two strings (invalid), leading candidates to overlook the need for explicit type conversion.

How to eliminate wrong answers

Option B is wrong because it still uses string indices (reader[i][1] and reader[i][2]) without conversion, so multiplication of strings still raises a TypeError. Option C is wrong because integer multiplication would fail if the data contains decimal values (e.g., '19.99'), and converting to float afterward does not fix the initial type error. Option D is wrong because it uses numeric indices (row[1], row[2]) instead of the column names 'Price' and 'Quantity', which would cause a KeyError if the CSV reader uses DictReader, or would access the wrong columns if the order differs.

227
MCQmedium

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

A.[1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 6]
B.[1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
C.[1, 2, 3, 4] [1, 2, 3, 5] [1, 2, 3, 5]
D.[1, 2, 3, 4] [1, 2, 3, 5] [1, 2, 3, 6]
AnswerA

Why this answer

The code creates a list a = [1, 2, 3, 4, 5] and assigns b = a (both reference the same list). The first two print(a) and print(b) output the original list [1, 2, 3, 4, 5]. Then b[3] = 6 changes the element at index 3 to 6, and del b[4] removes the element at index 4 (value 5).

Both modifications affect the same list object. The final print(a) outputs the modified list [1, 2, 3, 6]. Option A correctly shows the three outputs.

Exam trap

The PCEP exam often tests the misconception that `b = a` creates a new list copy, leading candidates to think changes to `b` do not affect `a`, or that `del` removes by value rather than by index.

How to eliminate wrong answers

Option B is wrong because it shows the third output as `[1, 2, 3, 4, 5]`, ignoring that `b[3] = 6` modifies the list in place and `del b[4]` removes the last element. Option C is wrong because it shows the first output as `[1, 2, 3, 4]` (missing the 5) and the second as `[1, 2, 3, 5]` (incorrect index change), misunderstanding that `b[3] = 6` replaces the value at index 3, not index 4. Option D is wrong because it shows the first output as `[1, 2, 3, 4]` (missing the 5) and the second as `[1, 2, 3, 5]`, again misidentifying which element is modified and the initial list length.

228
MCQmedium

A developer writes a function that modifies a global variable inside the function: count = 0 def increment(): count += 1 When called, an error occurs. What is the correct way to fix this?

A.Define count inside the function
B.Use the 'static' keyword
C.Pass count as an argument to the function
D.Use 'global count' inside the function
AnswerD

The global statement allows the function to modify the global variable.

Why this answer

To modify a global variable inside a function, the global keyword must be used to declare the variable as global.

229
MCQeasy

An application requires different messages based on temperature. Given: temp = 25 if temp > 30: print('Hot') elif temp > 20: print('Warm') else: print('Cool') What is the output?

A.No output
B.Hot
C.Cool
D.Warm
AnswerD

Temp is above 20, below 30.

Why this answer

The condition `temp > 30` is False (25 is not greater than 30), so the first `if` block is skipped. The `elif temp > 20` condition is True (25 > 20), so the `print('Warm')` statement executes, outputting 'Warm'. Option D is correct.

Exam trap

The PCEP exam often tests the misconception that `elif` is optional or that the `else` block will execute even when a preceding `elif` is True, leading candidates to incorrectly choose 'Cool'.

How to eliminate wrong answers

Option A is wrong because the code will always produce output since the `else` clause ensures at least one branch executes, and here the `elif` condition is True. Option B is wrong because `temp` is 25, which is not greater than 30, so the `if` block for 'Hot' does not run. Option C is wrong because the `elif` condition `temp > 20` is True, so the `else` block (which prints 'Cool') is never reached.

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

231
MCQhard

What is the output of the code in the exhibit?

A.[1, 2, 10, 20, 5]
B.[1, 10, 20, 4, 5]
C.[1, 2, 3, 10, 20, 4, 5]
D.[1, 10, 20, 3, 4, 5]
AnswerB

Correct replacement.

Why this answer

The code uses list slice assignment to replace the elements at indices 1 and 2 (the second and third elements) with the list [10, 20]. Starting from [1, 2, 3, 4, 5], after the assignment lst[1:3] = [10, 20], the list becomes [1, 10, 20, 4, 5]. This matches option B.

Exam trap

Python Institute often tests the distinction between `extend()` and `append()`, and the precise behavior of step slicing, leading candidates to mistakenly think `extend()` inserts elements at a specific position or that `[::2]` removes elements rather than selecting every second one.

How to eliminate wrong answers

Option A is wrong because it shows `[1, 2, 10, 20, 5]`, which incorrectly assumes the slice `[::2]` takes the first two elements and then appends `[10, 20]` before the last element, misunderstanding both the step slicing and the `extend()` behavior. Option C is wrong because it shows `[1, 2, 3, 10, 20, 4, 5]`, which incorrectly assumes `extend()` inserts the new list in the middle or that the slice retains all original elements. Option D is wrong because it shows `[1, 10, 20, 3, 4, 5]`, which incorrectly assumes `extend()` inserts at index 1 and that the slice only removes the second element, misrepresenting both the step slicing and the append position.

232
Multi-Selecthard

Which THREE of the following are valid ways to create a list with elements 1, 2, 3? (Choose Three)

Select 3 answers
A.[1,2,3]
B.list(range(1,4))
C.(1,2,3)
D.[x for x in range(1,4)]
E.{1,2,3}
AnswersA, B, D

Standard list literal.

Why this answer

It uses the literal list syntax with square brackets and commas to directly create a list containing the integers 1, 2, and 3. This is the most straightforward and explicit way to define a list in Python.

Exam trap

The PCEP exam often tests the distinction between list, tuple, and set literals, so candidates mistakenly choose curly-brace or parenthesis syntax as valid list creation methods.

233
MCQmedium

While debugging a Python script, you see the following error: 'IndentationError: expected an indented block'. The code appears to be correctly indented with spaces. What is the most likely cause?

A.You used the wrong number of spaces (e.g., 2 spaces instead of 4).
B.You forgot to include a colon at the end of a compound statement.
C.The script has a logic error in the condition.
D.You mixed tabs and spaces for indentation.
AnswerD

Mixture of tabs and spaces is a common cause of IndentationError.

Why this answer

Mixing tabs and spaces for indentation is a common cause of 'IndentationError: expected an indented block' even when the code appears correctly indented. Python 3 disallows mixing tabs and spaces; it uses the exact whitespace characters to determine block structure, and inconsistent usage triggers this error.

Exam trap

The PCEP exam often tests the misconception that any indentation inconsistency (like wrong number of spaces) causes an IndentationError, when in fact Python only cares about consistency and does not enforce a specific number of spaces.

How to eliminate wrong answers

Option A is wrong because using a consistent number of spaces (e.g., 2 instead of 4) does not cause an IndentationError; Python accepts any consistent indentation width. Option B is wrong because a missing colon at the end of a compound statement (like 'if', 'for', 'def') causes a 'SyntaxError', not an 'IndentationError'. Option C is wrong because a logic error in a condition does not produce an IndentationError; it would cause incorrect runtime behavior, not a syntax-level indentation failure.

234
MCQhard

A programmer needs to read a file line by line and process each line. Which of the following is the most memory-efficient and Pythonic approach?

A.with open('file.txt') as f: for line in f: print(line)
B.lines = open('file.txt').read().split('\n')
C.content = open('file.txt').read().splitlines()
D.for line in open('file.txt'): print(line)
AnswerA

Uses context manager and iterates lazily.

Why this answer

It uses a `with` statement to ensure the file is properly closed after the block, and iterating directly over the file object reads one line at a time without loading the entire file into memory. This is both memory-efficient and Pythonic, as it leverages the file object's built-in iterator.

Exam trap

The PCEP exam often tests the distinction between using a `with` statement for guaranteed file closure versus relying on implicit garbage collection, and the misconception that reading the entire file at once is acceptable for small files, ignoring the principle of memory efficiency.

How to eliminate wrong answers

Option B is wrong because it reads the entire file into memory with `.read()`, then splits into a list, which is memory-inefficient for large files and does not close the file explicitly (relying on garbage collection). Option C is wrong because it also reads the entire file into memory with `.read()` and then splits into lines, wasting memory and leaving the file handle open. Option D is wrong because it does not use a `with` statement, so the file is not guaranteed to be closed promptly; it relies on the file object being garbage-collected, which is not Pythonic and can lead to resource leaks.

235
Drag & Dropmedium

Order the steps to define and call a function 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

Function definition starts with def, then the body, parameters are optional, and calling the function executes it.

236
MCQeasy

A developer writes a while loop to count down from 10 to 1 and then stop. Which condition should be used?

A.while counter != 0:
B.while counter >= 0:
C.while counter < 10:
D.while counter > 0:
AnswerD

Correct: runs while counter is positive; stops when counter becomes 0.

Why this answer

The while loop must continue as long as the counter is greater than 0, counting down from 10 to 1. When counter becomes 0, the condition `counter > 0` evaluates to False, and the loop terminates, stopping exactly at 1.

Exam trap

Python Institute often tests the off-by-one error where candidates choose `>= 0` thinking they need to include 0, but the requirement to stop at 1 means the loop must not execute when counter is 0.

How to eliminate wrong answers

Option A is wrong because `while counter != 0:` would cause the loop to continue until counter becomes 0, but if counter starts at 10 and decrements, it will reach 0 and stop correctly; however, this condition is less intuitive and could cause an infinite loop if counter skips 0 (e.g., decrement by 2). Option B is wrong because `while counter >= 0:` would include 0, causing the loop to run one extra iteration when counter is 0, printing 0 instead of stopping at 1. Option C is wrong because `while counter < 10:` would start as True (since 10 < 10 is False) and never execute the loop body, or if counter starts below 10, it would count up, not down.

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

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

239
MCQeasy

What is the output when the user enters 25?

A.Error
B.2525
C.25
D.50
AnswerB

Correct. String replication.

Why this answer

When the user enters 25, the input() function returns the string "25". The print() function then concatenates the string "25" with itself using the + operator, resulting in "2525". This is because the + operator performs string concatenation when both operands are strings, not numeric addition.

Exam trap

Python Institute often tests the distinction between string concatenation and numeric addition, exploiting the fact that input() returns a string, so candidates mistakenly assume the + operator will perform arithmetic.

How to eliminate wrong answers

Option A is wrong because no error occurs; input() always returns a string, and concatenating two identical strings is a valid operation. Option C is wrong because it assumes the output is a single "25", but the code explicitly prints the concatenation of two copies of the input string. Option D is wrong because it assumes numeric addition (25+25=50), but the + operator concatenates strings, not numbers, since input() returns a string.

240
Multi-Selectmedium

Which TWO of the following expressions evaluate to True?

Select 2 answers
A.bool('')
B.bool([])
C.bool(1)
D.bool('False')
E.bool(0)
AnswersC, D

Non-zero integer is True.

Why this answer

`bool(1)` converts the integer 1 to a Boolean, and in Python any non-zero numeric value is considered truthy, so `bool(1)` returns `True`. Option D is correct because `bool('False')` converts the non-empty string `'False'` to a Boolean; in Python, any non-empty string is truthy, regardless of its textual content, so it returns `True`.

Exam trap

The trap here is that candidates often mistakenly think the string `'False'` is falsy because it looks like the Boolean `False`, but Python evaluates truthiness based on the object's type and content, not its string representation.

241
MCQhard

What is the result of the expression: print(2 ** 3 ** 2) ?

A.512
B.256
C.64
D.128
AnswerA

2**(3**2) = 2**9 = 512.

Why this answer

The expression `2 ** 3 ** 2` uses the exponentiation operator `**`, which in Python is right-associative. This means it is evaluated as `2 ** (3 ** 2)`, not `(2 ** 3) ** 2`. First, `3 ** 2` equals 9, then `2 ** 9` equals 512.

Therefore, option A is correct.

Exam trap

The trap here is that many candidates assume exponentiation is left-associative like most other arithmetic operators, leading them to compute `(2 ** 3) ** 2 = 64` instead of the correct right-associative `2 ** (3 ** 2) = 512`.

How to eliminate wrong answers

Option B (256) is wrong because it would result from `(2 ** 3) ** 2` (i.e., 8 ** 2 = 64) and then incorrectly doubling, not from the correct right-associative evaluation. Option C (64) is wrong because it represents the result of `(2 ** 3) ** 2` (8 squared), which is the left-associative misinterpretation of the expression. Option D (128) is wrong because it would come from `2 ** 7` (a miscalculation of the exponent), not from the correct `2 ** 9`.

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

243
MCQmedium

A program calculates BMI. User inputs weight and height as strings. Which line correctly converts to float?

A.weight = float(input)
B.weight = input().float()
C.weight = float(input())
D.weight = input(float())
AnswerC

Correct; input() returns string, float() converts.

Why this answer

`float(input())` first reads the user's input as a string via `input()`, then converts that string to a floating-point number using the `float()` function. This is the standard Python pattern for converting user input to a numeric type.

Exam trap

Python Institute often tests the distinction between calling a function (`float(input())`) versus referencing it (`float(input)`) or chaining a non-existent method (`input().float()`), exploiting the common confusion that methods and functions are interchangeable.

How to eliminate wrong answers

Option A is wrong because `float(input)` passes the function object `input` itself, not the result of calling it, causing a TypeError. Option B is wrong because `input().float()` attempts to call a method named `float` on a string object, but strings have no such method; the correct approach is to use the built-in `float()` function. Option D is wrong because `input(float())` tries to call `input()` with a float argument (the result of `float()`), which is meaningless and will raise a TypeError since `input()` expects an optional string prompt, not a number.

244
MCQhard

A function is supposed to modify a list passed as argument by appending an element. However, after calling the function, the original list remains unchanged. Which is the most likely cause?

A.The list is immutable.
B.The list is a tuple.
C.The function uses a local variable that shadows the global list.
D.The function reassigns the list parameter instead of mutating it.
AnswerD

Reassignment creates a new local variable, leaving original untouched.

Why this answer

In Python, when a list is passed to a function, the parameter refers to the same list object. If the function reassigns the parameter (e.g., `lst = [1, 2, 3]`), it only changes the local reference, not the original list. To modify the original list, the function must mutate it in-place using methods like `append()` or `extend()`, not reassign the parameter.

Exam trap

The PCEP exam often tests the distinction between mutating an object in-place versus reassigning the parameter name, exploiting the common misconception that reassigning a parameter inside a function will affect the original argument.

How to eliminate wrong answers

Option A is wrong because lists in Python are mutable objects; they can be modified in-place. Option B is wrong because a tuple is an immutable sequence, but the question explicitly states a list is passed, so this is a category error. Option C is wrong because while shadowing a global variable can cause confusion, the core issue here is that the function reassigns the parameter (a local variable) rather than mutating the list object itself; shadowing alone does not prevent mutation of the passed list.

245
MCQmedium

A team is developing a script that processes user input. They want to ensure that if the user enters a non-numeric value when asked for age, the program does not crash. Which approach should they use?

A.Use raw_input() and then int()
B.Use input() with a type check after input
C.Use int(input()) within a try-except block
D.Use a while loop to check if input.isdigit()
AnswerC

This catches ValueError and allows graceful handling.

Why this answer

Wrapping `int(input())` in a `try-except` block catches the `ValueError` that occurs when `int()` receives a non-numeric string. This prevents the program from crashing and allows graceful handling of invalid input, which is the standard Pythonic approach for robust user input validation.

Exam trap

The PCEP exam often tests the misconception that type checking after `input()` can prevent crashes, but candidates forget that `input()` always returns a string, making type checks like `isinstance()` useless without conversion, and that `isdigit()` is insufficient for numeric validation beyond simple positive integers.

How to eliminate wrong answers

Option A is wrong because `raw_input()` does not exist in Python 3 (it was renamed to `input()` in Python 2), and even if corrected, calling `int()` directly on non-numeric input will raise a `ValueError` and crash the program. Option B is wrong because using `input()` with a type check after input (e.g., `isinstance(value, int)`) is ineffective since `input()` always returns a string; the type check will never detect a non-numeric string as an integer, and the conversion to `int` would still crash if attempted. Option D is wrong because `input().isdigit()` only checks if the string consists entirely of digits, which fails for negative numbers, floats, or empty strings, and it does not handle the conversion or exception; the program would still crash if `int()` is called on a non-digit string.

246
Multi-Selectmedium

Which three of the following are Python arithmetic operators? (Choose three.)

Select 3 answers
A.+
B.|
C.-
D.&
E.*
AnswersA, C, E

Addition operator

Why this answer

The plus sign (+) is a standard Python arithmetic operator used for addition. It performs numeric addition when both operands are numbers, and also supports string concatenation, but its primary role in arithmetic contexts is addition.

Exam trap

Python Institute often tests the distinction between arithmetic operators and bitwise operators, trapping candidates who mistake the vertical bar or ampersand for arithmetic symbols due to their visual similarity to plus or multiplication signs.

247
MCQhard

A script uses 'import math' then calls 'math.sqrt(-1)'. What is the outcome?

A.ValueError
B.NaN
C.A complex number
D.AttributeError
AnswerA

math domain error because sqrt of negative number is not defined in real math.

Why this answer

`math.sqrt()` in Python's math module does not support negative arguments; it raises a `ValueError` when given a negative number, as the function is designed for real numbers only. The error message is 'math domain error', indicating the input is outside the domain of the mathematical function.

Exam trap

The trap here is that candidates mistakenly think `math.sqrt()` can handle negative numbers by returning a complex number or NaN, confusing it with `cmath.sqrt()` or the behavior of some other languages' math libraries.

How to eliminate wrong answers

Option B is wrong because `math.sqrt(-1)` does not return NaN (Not a Number); Python's math module raises an exception rather than returning a special floating-point value like NaN. Option C is wrong because `math.sqrt()` does not return a complex number; to get a complex result, you must use `cmath.sqrt()` from the `cmath` module, which is designed for complex arithmetic. Option D is wrong because `AttributeError` would occur if the function `sqrt` did not exist on the `math` module, but `math.sqrt` is a valid attribute; the error is a `ValueError` due to the invalid argument, not a missing attribute.

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

249
Multi-Selectmedium

Which TWO of the following statements about Python's for loop are correct? (Choose Two)

Select 2 answers
A.It can be used with a while loop condition
B.It can iterate over any sequence
C.It always executes at least once
D.It can be used with an else clause
E.It is the only loop in Python
AnswersB, D

For works with lists, tuples, strings, etc.

Why this answer

A `for` loop in Python is designed to iterate over any iterable sequence, such as lists, tuples, strings, dictionaries, or ranges. This is a fundamental property of the `for` loop, which retrieves each item from the sequence in order until the sequence is exhausted.

Exam trap

The PCEP exam often tests the misconception that a `for` loop always executes at least once, but in reality it can iterate zero times over an empty sequence, and they also test the less-known fact that `for` loops support an `else` clause.

250
MCQhard

Refer to the exhibit. What is the final value of x after executing the code?

A.[1, 1, 1]
B.[3, 2, 1]
C.[1, 2, 3]
D.[3, 1, 2]
AnswerC

Incorrect because the list is not preserved; x is reassigned to the last element (3).

Why this answer

The code uses `x` as both the list variable and the loop variable. During iteration, `x` is reassigned to each element. After the loop, `x` holds the last element, which is `3`.

Since `3` is not among the options, none of the given options is correct.

Exam trap

The trap is that students think the list remains unchanged, but if the loop variable is named the same as the list, the list variable is overwritten during iteration.

How to eliminate wrong answers

Option A is wrong because it suggests the list becomes [1, 1, 1], which would require overwriting all elements with 1, but the loop does not assign to list elements. Option B is wrong because it suggests the list becomes [3, 2, 1], which would require reversing or decrementing, but the loop simply iterates without modifying the list. Option D is wrong because it suggests the list becomes [3, 1, 2], which would require a specific reordering not present in the code; the loop does not alter the list order.

251
MCQeasy

A programmer writes: x = 5; y = "10"; z = x + y. What will happen?

A.Prints error but continues execution
B.Prints 510
C.TypeError: unsupported operand type(s) for +: 'int' and 'str'
D.Prints 15
AnswerC

Correct; Python raises TypeError for mismatched types.

Why this answer

Python does not implicitly convert between incompatible types for the '+' operator. When an integer (int) and a string (str) are used with '+', Python raises a TypeError, as it cannot decide whether to perform arithmetic addition or string concatenation without explicit conversion.

Exam trap

Python Institute often tests the misconception that Python will automatically convert types to make the operation work, either by treating the integer as a string (concatenation) or the string as a number (addition), when in fact Python raises a TypeError for mixed-type '+' operations.

How to eliminate wrong answers

Option A is wrong because Python does not print an error and continue execution; it raises an unhandled TypeError that stops the program unless caught with a try/except block. Option B is wrong because it assumes Python will automatically convert the integer to a string and concatenate them as '510', but Python does not perform implicit type coercion for '+' between int and str. Option D is wrong because it assumes Python will convert the string '10' to an integer and perform numeric addition to get 15, but Python does not implicitly convert strings to integers for arithmetic operations.

252
MCQmedium

What is the output of the code?

A.<class 'str'>
B.<class 'int'>
C.<class 'float'>
D.<class 'bool'>
AnswerC

Correct. Division yields a float.

Why this answer

The code uses the `type()` function to determine the data type of the result of the expression `10 / 3`. In Python 3, the `/` operator always performs true division, which returns a floating-point number even if the operands are integers. Therefore, `10 / 3` evaluates to `3.3333333333333335` (a float), and `type()` returns `<class 'float'>`.

Option C is correct.

Exam trap

Python Institute often tests the distinction between `/` (true division) and `//` (floor division) in Python 3, and the trap here is that candidates mistakenly think integer division with `/` yields an integer, confusing it with Python 2 behavior or the `//` operator.

How to eliminate wrong answers

Option A is wrong because the result of `10 / 3` is not a string; the `/` operator does not produce a string type. Option B is wrong because true division (`/`) in Python 3 never returns an integer; it always returns a float, even when the division is exact (e.g., `4 / 2` returns `2.0`). Option D is wrong because the result is not a Boolean; division does not yield a `bool` type, and the expression is not a comparison or logical operation.

253
MCQeasy

Which of the following code snippets will correctly assign the integer 10 to the variable 'x'?

A.x == 10
B.x := 10
C.10 = x
D.x = 10
AnswerD

Correct assignment.

Why this answer

In Python, the assignment operator is a single equals sign (=), which binds the value on the right to the variable name on the left. The statement `x = 10` assigns the integer 10 to the variable 'x'.

Exam trap

The PCEP exam often tests the confusion between the assignment operator (`=`) and the equality operator (`==`), as well as the misuse of the walrus operator (`:=`) as a standalone assignment, to catch candidates who are not precise about Python syntax.

How to eliminate wrong answers

Option A is wrong because `==` is the equality comparison operator, not an assignment operator; it would evaluate to a Boolean (True or False) and not assign a value. Option B is wrong because `:=` is the walrus operator (assignment expression) introduced in Python 3.8, which is used within expressions and requires parentheses in most contexts; it is not a standalone assignment statement. Option C is wrong because Python does not allow assignment to a literal; the left side of an assignment must be a variable name, not a value like 10.

254
MCQhard

Given 'a = 10; b = 3; c = a // b; d = a % b', what is the value of c + d?

A.4
B.5
C.7
D.6
AnswerA

Floor division gives 3, modulo gives 1, sum is 4.

Why this answer

In Python, the // operator performs floor division, so a // b = 10 // 3 = 3. The % operator returns the remainder, so a % b = 10 % 3 = 1. Therefore, c + d = 3 + 1 = 4, making option A correct.

Exam trap

Python Institute often tests the distinction between floor division (//) and true division (/), and the trap here is that candidates may mistakenly use regular division (10 / 3 ≈ 3.33) and then add the remainder incorrectly, or forget that // and % are complementary operations that together reconstruct the original dividend.

How to eliminate wrong answers

Option B (5) is wrong because it might result from incorrectly using regular division (10 / 3 ≈ 3.33) and rounding up, or from adding the quotient (3) and remainder (1) incorrectly as 4, not 5. Option C (7) is wrong because it could come from adding the quotient (3) and the divisor (3) plus the remainder (1), or from miscomputing the remainder as 4 (10 % 3 = 1, not 4). Option D (6) is wrong because it might arise from adding the quotient (3) and the divisor (3) together, ignoring the remainder, or from a miscalculation of floor division as 2.

255
MCQeasy

A programmer wants to create a list of even numbers from 0 to 10 inclusive. Which list comprehension is correct?

A.[x for x in range(0,11) if x%2==0]
B.[x for x in range(0,10) if x%2==0]
C.[x for x in range(0,11) if x%2]
D.[x for x in range(0,11) if x%2==1]
AnswerA

Correct condition for even.

Why this answer

It uses `range(0,11)` to generate numbers from 0 to 10 inclusive, and the condition `if x%2==0` selects only even numbers (where the remainder when divided by 2 is 0). This matches the requirement exactly.

Exam trap

Python Institute often tests the distinction between `range(0,11)` and `range(0,10)` to catch candidates who forget that the stop value is exclusive, and the use of truthy/falsy values in conditions (e.g., `if x%2` instead of `if x%2==0`) to confuse even vs. odd selection.

How to eliminate wrong answers

Option B is wrong because `range(0,10)` generates numbers from 0 to 9, missing the number 10, so it does not include 10 as required. Option C is wrong because `if x%2` evaluates to True for odd numbers (since any non-zero remainder is truthy), so it selects odd numbers instead of even numbers. Option D is wrong because `if x%2==1` also selects odd numbers (remainder 1), not even numbers.

256
MCQeasy

Which of the following is a valid Python variable name?

A.2var
B._var
C.my-var
D.var$name
AnswerB

Underscores are allowed and commonly used.

Why this answer

(_var) is correct because Python variable names must start with a letter or an underscore, and can contain letters, digits, or underscores. The underscore is a valid starting character, making _var a legal identifier.

Exam trap

Python Institute often tests the misconception that hyphens or special characters like '$' are allowed in variable names, or that digits can start a name, because candidates confuse Python's rules with those of other languages like JavaScript or PHP.

How to eliminate wrong answers

Option A is wrong because Python variable names cannot begin with a digit; '2var' starts with '2', which violates the syntax rule. Option C is wrong because the hyphen '-' is not allowed in Python identifiers; only underscores, letters, and digits are permitted. Option D is wrong because the dollar sign '$' is not a valid character in Python variable names; identifiers are limited to alphanumeric characters and underscores.

257
MCQmedium

A program uses a variable named 'list' that shadows the built-in list type. Later, the code tries to create a new list using list([1,2,3]) but gets a TypeError. What is the most likely cause?

A.The argument [1,2,3] is invalid because it contains integers.
B.The variable 'list' is now an integer or other non-callable type.
C.The list constructor expects a tuple, not a list.
D.The code is missing an import for the list type.
AnswerB

Because 'list' was reassigned, it no longer refers to the built-in function.

Why this answer

When a variable named 'list' is assigned a value (e.g., an integer), it shadows the built-in `list` type in the current scope. Later, calling `list([1,2,3])` attempts to call the variable `list` as a function, but since it now holds a non-callable object (like an integer), Python raises a TypeError. This is a classic name-shadowing issue in Python.

Exam trap

Python Institute often tests the concept of name shadowing, where candidates mistakenly think the error is due to invalid arguments or missing imports, rather than recognizing that reassigning a built-in name makes it non-callable.

How to eliminate wrong answers

Option A is wrong because `[1,2,3]` is a perfectly valid list literal containing integers, and the list constructor accepts any iterable, including lists. Option C is wrong because the list constructor accepts any iterable (list, tuple, string, etc.), not just tuples; a list argument is valid. Option D is wrong because `list` is a built-in type in Python and does not require any import; it is always available in the global namespace.

258
MCQhard

A Python script uses the following code to open a file: f = open('data.txt', 'w'). The programmer then writes multiple lines to the file. After writing, which of the following is the BEST practice to ensure data integrity?

A.Call f.close() after writing.
B.Call f.flush() after writing.
C.No action needed; Python automatically closes files.
D.Use a with statement to open the file.
AnswerD

Ensures proper closing even on exceptions.

Why this answer

Using a `with` statement ensures that the file is automatically closed when the block exits, even if an exception occurs. This guarantees that all buffered data is flushed to disk, preventing data loss or corruption. It is the recommended best practice in Python for reliable file handling.

Exam trap

Python Institute often tests the misconception that Python automatically closes files or that calling `close()` or `flush()` individually is sufficient, when in fact the `with` statement is the only guaranteed way to ensure proper cleanup and data integrity.

How to eliminate wrong answers

Option A is wrong because calling `f.close()` alone does not guarantee data integrity if an exception occurs before the call; it also requires explicit management of the close operation. Option B is wrong because `f.flush()` only forces the internal buffer to be written to the operating system, but does not ensure the file is closed or that data is fully written to disk (the OS may still cache it). Option C is wrong because Python does not automatically close files; the file remains open until garbage collection, which can lead to resource leaks and potential data loss.

259
MCQeasy

A data analyst needs to read two integers from the user and compute their average as a float. The current code: a = int(input()) b = int(input()) avg = a + b / 2 print(avg) The output is always incorrect when a=5 and b=7 (expected 6.0, actual 8.5). The analyst cannot identify the bug. What is the root cause and correct fix?

A.The input function is not converting correctly; use float(input()) instead.
B.The print function is rounding the result; use print("{:.1f}".format(avg)).
C.The addition and division have wrong operator precedence; use parentheses: (a + b) / 2.
D.The division operator / always returns an integer; use // instead.
AnswerC

Without parentheses, division happens first.

Why this answer

In Python, the division operator `/` has higher precedence than addition `+`, so `a + b / 2` is evaluated as `a + (b / 2)`, not `(a + b) / 2`. For a=5 and b=7, this computes `5 + (7 / 2) = 5 + 3.5 = 8.5` instead of the expected `(5 + 7) / 2 = 12 / 2 = 6.0`. Adding parentheses around `a + b` forces the addition to occur first, yielding the correct average as a float.

Exam trap

Python Institute often tests operator precedence by presenting a simple arithmetic expression without parentheses, leading candidates to overlook the order of operations and incorrectly blame input conversion or output formatting.

How to eliminate wrong answers

Option A is wrong because the issue is not about input conversion; `int(input())` correctly reads integers, and using `float(input())` would not fix the operator precedence bug. Option B is wrong because the print function does not round the result; the actual computed value is 8.5, not 6.0, so formatting the output would still show 8.5. Option D is wrong because the `/` operator in Python 3 always returns a float (e.g., 7/2 = 3.5), and using `//` would perform floor division, yielding an integer result (e.g., 12//2 = 6) but would break for odd sums (e.g., 5+6=11, 11//2=5, not 5.5), so it is not the correct fix.

260
Multi-Selecteasy

Which TWO of the following expressions evaluate to True? (Choose two.)

Select 2 answers
A.'a' > 'b'
B.5 > 10
C.3 == 3
D.bool(0)
E.not False
AnswersC, E

True, equal.

Why this answer

The equality operator '==' compares the two operands and returns True if they are equal. Since 3 is indeed equal to 3, the expression evaluates to True.

Exam trap

Python Institute often tests the distinction between truthy/falsy values and the behavior of bool() with numeric zero, leading candidates to mistakenly think bool(0) returns True.

261
MCQhard

Given the code: a = [1, 2, 3]; b = a; b.append(4). What is the value of a?

A.[1, 2, 3, 4]
B.Error
C.[1, 2, 3]
D.[1, 2, 3, [4]]
AnswerA

Both a and b refer to the same list.

Why this answer

In Python, variables hold references to objects, not copies. When `b = a` is executed, both `a` and `b` point to the same list object in memory. The `append()` method modifies the list in-place, so the change is visible through both references.

Thus, `a` becomes `[1, 2, 3, 4]`.

Exam trap

The trap here is that Cisco tests whether candidates understand that assignment with `=` does not create a new copy for mutable objects; many mistakenly think `b = a` creates a separate list, leading them to choose option C.

How to eliminate wrong answers

Option B is wrong because `append()` is a valid list method and does not raise an error; it modifies the list in-place and returns `None`, but the code does not assign that return value. Option C is wrong because it assumes `b = a` creates a copy of the list, but Python uses reference semantics for lists, so modifications via `b` affect `a`. Option D is wrong because `append(4)` adds the integer `4` as a single element, not as a nested list; the result is `[1, 2, 3, 4]`, not `[1, 2, 3, [4]]`.

262
Multi-Selectmedium

Which TWO of the following Python data types are mutable?

Select 2 answers
A.list
B.str
C.tuple
D.int
E.dict
AnswersA, E

Lists can be modified in place.

Why this answer

Lists in Python are mutable, meaning their elements can be changed, added, or removed after creation. This is a fundamental property of the list type, which supports operations like append(), extend(), and item assignment.

Exam trap

Python Institute often tests the misconception that strings or tuples are mutable because they support indexing and slicing, but candidates must remember that these operations return new objects rather than modifying the original.

263
MCQeasy

A developer wants to store a person's age. Which of these variable names is invalid?

A._age
B.3rd_age
C.Age
D.age_3
AnswerB

Variable cannot start with a number.

Why this answer

In Python, variable names must start with a letter or an underscore, not a digit. Option B (`3rd_age`) begins with a digit, which violates Python's identifier naming rules and will raise a `SyntaxError` if used in code.

Exam trap

Python Institute often tests the rule that variable names cannot start with a digit, tricking candidates who focus on case sensitivity or underscores instead of the initial character restriction.

How to eliminate wrong answers

Option A is wrong because `_age` starts with an underscore, which is allowed in Python variable names. Option C is wrong because `Age` starts with a letter and is case-sensitive but valid. Option D is wrong because `age_3` starts with a letter and contains an underscore and digit, both permitted after the first character.

264
MCQeasy

A junior developer is writing a script to calculate the total cost of items in a shopping cart. The script uses variables item_price (float) and quantity (int). The code is: item_price = 2.5 quantity = 3 total = item_price * quantity print("Total: " + total) When run, this code raises a TypeError. The developer is confused because the multiplication seems correct. What is the most likely issue and the correct fix?

A.The variable total is being overwritten by the print statement; use a different variable name.
B.The multiplication should be written as int(item_price) * quantity to ensure integer result.
C.The variable names are too descriptive; rename them to a and b to avoid confusion.
D.The print function cannot concatenate a string with a float; convert total to string using str(total).
AnswerD

Concatenation requires both operands to be strings.

Why this answer

The `print` function in Python expects all arguments to be strings when using the `+` operator for concatenation. The variable `total` is a float (result of multiplying a float by an int), and Python does not implicitly convert it to a string. The error is a `TypeError: can only concatenate str (not 'float') to str`.

The fix is to explicitly convert `total` to a string using `str(total)` before concatenation.

Exam trap

Python Institute often tests the distinction between arithmetic operations (which work across numeric types) and string concatenation (which requires explicit type conversion), trapping candidates who assume Python will automatically convert a float to a string when using the `+` operator.

How to eliminate wrong answers

Option A is wrong because the `print` statement does not overwrite the variable `total`; it only reads its value. The error is a type mismatch in concatenation, not a variable naming issue. Option B is wrong because converting `item_price` to an integer would lose the decimal precision (2.5 becomes 2), and the multiplication result would be incorrect for a shopping cart total.

The error is not about integer vs. float multiplication; it's about string concatenation. Option C is wrong because variable names being descriptive is a best practice, not a cause of errors. Renaming them to `a` and `b` would not fix the `TypeError` and would reduce code readability.

265
MCQmedium

You are a data analyst at a retail company. You have a list of sales figures stored as strings in a list: sales = ['100', '200', '300']. You need to calculate the total sum. A colleague suggests using: total = sum(sales). However, this raises a TypeError because sum() requires numeric values. Which approach should you take to correctly calculate the total as an integer?

A.Use total = sum(sales) and catch TypeError
B.Use total = sum(int(s) for s in sales)
C.Use total = sum(map(str, sales))
D.Use total = 0; for s in sales: total += s
AnswerB

Converts each string to int using a generator expression, then sums the integers. This is the correct approach.

Why this answer

Option B uses a generator expression to convert each string element to an integer before passing them to sum(). Option A attempts to catch the TypeError but doesn't convert the strings to numbers. Option C uses str() to convert the numbers to strings, so sum() still receives strings and raises a TypeError.

Option D attempts to concatenate strings with +=, resulting in a string, not a numeric total.

Exam trap

Python Institute often tests the misconception that `sum()` can implicitly convert strings to numbers, or that catching an exception is a valid workaround, when in fact explicit conversion via `int()` is required.

How to eliminate wrong answers

Option A is wrong because catching a `TypeError` does not fix the underlying problem—the strings are still not converted to numbers, so the sum would still fail or require additional handling. Option D is wrong because `total += s` attempts to add a string to an integer, which raises a `TypeError` due to incompatible types; the loop must convert each `s` to an integer first.

266
Multi-Selecteasy

Which of the following are valid Python variable names? (Choose two.)

Select 2 answers
A.for
B.data_1
C._count
D.2nd_place
E.my-var
AnswersB, C

Letters, digits, and underscores are allowed, and the name does not start with a digit.

Why this answer

(data_1) is correct because Python variable names can contain letters, digits, and underscores, but must not start with a digit. 'data_1' starts with a letter and includes an underscore and digit, all of which are allowed.

Exam trap

The PCEP exam often tests the distinction between hyphens (which are not allowed) and underscores (which are allowed), and the rule that keywords like 'for' cannot be used as variable names, even though they look like valid identifiers.

267
Multi-Selectmedium

Which TWO of the following are immutable data types in Python?

Select 2 answers
A.str
B.set
C.dict
D.list
E.tuple
AnswersA, E

Immutable: string objects cannot be changed.

Why this answer

Strings (str) in Python are immutable, meaning once a string object is created, its content cannot be changed. Any operation that appears to modify a string actually creates a new string object in memory, leaving the original unchanged.

Exam trap

The PCEP exam often tests the distinction between mutable and immutable types by pairing tuple (immutable) with list (mutable), hoping candidates confuse tuple's immutability with list's mutability, or mistakenly think that because a tuple can contain mutable objects, the tuple itself is mutable.

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

269
MCQhard

Which of the following is an invalid variable name in Python?

A._myVar
B.myVar
C.my-var
D.my_var
AnswerC

Invalid; hyphens are not allowed in identifiers.

Why this answer

'my-var' contains a hyphen, which is not allowed in Python variable names. Python identifiers can only include letters, digits, and underscores, and cannot start with a digit. The hyphen is interpreted as a minus operator, making 'my-var' a syntax error.

Exam trap

The PCEP exam often tests the misconception that hyphens are acceptable in variable names because they appear in other languages (like JavaScript object keys) or in file names, but Python strictly prohibits them in identifiers.

How to eliminate wrong answers

Option A is wrong because '_myVar' is a valid variable name; underscores are allowed and commonly used for private or internal variables. Option B is wrong because 'myVar' follows Python naming rules (letters and underscores, no special characters). Option D is wrong because 'my_var' is valid; underscores are permitted and often used in snake_case naming conventions.

270
MCQmedium

Which list method modifies the list in place by adding all elements of another iterable to the end?

A.+ operator
B.insert()
C.append()
D.extend()
AnswerD

Expands the list with elements from an iterable.

Why this answer

The `extend()` method modifies the list in place by appending all elements from the provided iterable (e.g., another list, tuple, or string) to the end. It does not return a new list; it mutates the original list directly, which is the behavior described in the question.

Exam trap

Python Institute often tests the distinction between `append()` and `extend()` — the trap is that candidates confuse adding an iterable as a single element (append) with adding its individual elements (extend), especially when the iterable is a list or string.

How to eliminate wrong answers

Option A is wrong because the `+` operator creates a new list by concatenating two lists, leaving the original lists unchanged — it does not modify a list in place. Option B is wrong because `insert()` adds a single element at a specified index, not all elements of an iterable to the end. Option C is wrong because `append()` adds its argument as a single element (even if it is an iterable) to the end of the list, not the individual elements of an iterable.

271
MCQhard

A developer needs to check if all elements in a list of integers are even. Which code correctly implements this?

A.all_even = all(num % 2 for num in mylist)
B.all_even = any(num % 2 == 0 for num in mylist)
C.all_even = True for num in mylist: if num % 2 != 0: all_even = False break
D.all_even = False for num in mylist: if num % 2 == 0: all_even = True else: all_even = False
AnswerC

Correctly breaks on first odd.

Why this answer

It initializes `all_even` to `True`, then iterates through the list. If any element is odd (`num % 2 != 0`), it sets `all_even` to `False` and breaks out of the loop early, which is an efficient and correct way to check that all elements are even.

Exam trap

Python Institute often tests the misconception that `all()` with a condition like `num % 2` checks for even numbers, when in fact it checks for truthy remainders (odd numbers), leading candidates to incorrectly select Option A.

How to eliminate wrong answers

Option A is wrong because `all(num % 2 for num in mylist)` checks if every remainder is truthy (non-zero), which would be True only if all numbers are odd, not even. Option B is wrong because `any(num % 2 == 0 for num in mylist)` returns True if at least one element is even, not if all are even. Option D is wrong because it sets `all_even` to `True` whenever it encounters an even number, but then resets it to `False` on an odd number; however, if the list contains only even numbers, it will remain `True` only if the last element is even, but the logic is flawed because it does not break early and incorrectly handles the flag — for example, with `[2, 4, 6]` it works, but with `[2, 3, 4]` it ends as `False` (correct), but the approach is inefficient and conceptually incorrect because it toggles the flag on every element rather than checking the invariant.

272
Multi-Selectmedium

Which FOUR of the following are valid ways to create a list with elements 1, 2, 3? (Choose four.)

Select 4 answers
A.[1, 2, 3,]
B.list(range(1, 4))
C.[1, 2, 3]
D.list(1, 2, 3)
E.list((1, 2, 3))
AnswersA, B, C, E

Correct. A trailing comma is allowed in Python list literals, so [1, 2, 3,] creates a list with elements 1, 2, 3.

Why this answer

Options A, B, C, and E are all valid ways. A: list literal with trailing comma; B: list() constructor with range; C: standard list literal; E: list() constructor with a tuple. Option D is invalid because list() expects a single iterable argument, not multiple arguments.

Exam trap

Python Institute often tests the distinction between the `list()` constructor requiring a single iterable argument versus the mistaken belief that it accepts multiple positional arguments, as in option D.

273
MCQeasy

Which code correctly creates a list of squares for numbers 1 to 5 using a list comprehension?

A.squares = [x**2 for x in range(5)]
B.squares = [x^2 for x in (1,2,3,4,5)]
C.squares = [x**2 for x in range(1,6)]
D.squares = [x^2 for x in [1,2,3,4,5]]
AnswerC

Correct; range(1,6) gives 1-5 and ** is exponent.

Why this answer

It uses the proper syntax for a list comprehension: `[expression for item in iterable]`. Here, `x**2` computes the square, and `range(1,6)` generates numbers 1 through 5 (since range excludes the stop value). This produces the list `[1, 4, 9, 16, 25]`.

Exam trap

Python Institute often tests the distinction between `**` (exponentiation) and `^` (bitwise XOR), as well as the correct use of `range()` boundaries, to catch candidates who confuse operators or off-by-one errors.

How to eliminate wrong answers

Option A is wrong because `range(5)` generates numbers 0 through 4, not 1 through 5, so the list would include `0**2 = 0` and miss `5**2 = 25`. Option B is wrong because `x^2` uses the bitwise XOR operator, not exponentiation, so it computes `x XOR 2` instead of `x**2`. Option D is wrong because `x^2` again uses the bitwise XOR operator, not exponentiation, and although the iterable is correct, the operation is incorrect.

274
MCQhard

A developer runs the code from the exhibit and gets the error shown. Which of the following is the most likely cause?

A.There is a typo in the variable name.
B.The variable 'result' was never assigned a value.
C.The print function requires an import.
D.The variable 'result' is a string, not an integer.
AnswerB

NameError occurs when variable is not defined.

Why this answer

The error message indicates that the variable 'result' is referenced before it has been assigned any value. In Python, using a variable that has never been assigned raises a NameError. The code attempts to print 'result', but no assignment to 'result' exists in the provided code, so Python cannot resolve the name.

Exam trap

The PCEP exam often tests the distinction between a variable that exists but has the wrong type (TypeError) and a variable that has never been assigned (NameError), leading candidates to incorrectly focus on type mismatches instead of the missing assignment.

How to eliminate wrong answers

Option A is wrong because a typo in the variable name would still cause a NameError, but the error message would reference the misspelled name, not 'result'. Option C is wrong because the print function is a built-in in Python 3 and does not require any import; it is always available. Option D is wrong because the error is a NameError, not a TypeError; the variable 'result' does not exist at all, so its type is irrelevant.

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

276
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().

277
MCQhard

A programmer has a list of tuples representing (product, price) and wants to find the highest price. Which code correctly finds the maximum price?

A.max_price = max(prices, key=lambda x: x[1])
B.max_price = max([price for product, price in prices])
C.max_price = 0; for p in prices: if p[1] > max_price: max_price = p[1]
D.max_price = sorted(prices, key=lambda x: x[1])[-1]
AnswerB

Correct; list comprehension extracts prices, then max finds the largest.

Why this answer

Ly uses a list comprehension to extract all prices from the tuples, then passes that list to the built-in `max()` function, which returns the highest numeric value. This directly solves the problem of finding the maximum price without any unnecessary complexity.

Exam trap

Python Institute often tests the difference between `max()` returning the element that maximizes the key versus returning the key value itself, leading candidates to incorrectly choose option A when they want just the price.

How to eliminate wrong answers

Option A is wrong because `max(prices, key=lambda x: x[1])` returns the entire tuple with the highest price, not just the price itself. Option C is wrong because it initializes `max_price` to 0, which will fail if all prices are negative (the maximum would remain 0 instead of the actual highest negative price). Option D is wrong because `sorted(prices, key=lambda x: x[1])[-1]` returns the entire tuple with the highest price, not just the price value.

278
Multi-Selecteasy

Which TWO data types are immutable in Python?

Select 2 answers
A.str
B.set
C.list
D.dict
E.int
AnswersA, E

Immutable. Strings cannot be modified in-place.

Why this answer

Strings (str) are immutable in Python, meaning once a string object is created, its content cannot be changed; any operation that appears to modify a string actually creates a new string object. Option E is correct because integers (int) are also immutable; when you perform arithmetic on an integer, a new integer object is created rather than modifying the original.

Exam trap

The PCEP exam often tests the misconception that 'immutable' means the variable cannot be reassigned, but immutability refers to the object itself, not the variable binding; candidates may incorrectly think lists or dicts are immutable because they can reassign the variable.

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

280
MCQmedium

A developer writes: print(10 * '5'). What is the output?

A.10
B.50
C.5
D.5555555555
AnswerD

String repetition.

Why this answer

In Python, the multiplication operator (*) when used with a string and an integer performs string repetition. The expression 10 * '5' repeats the string '5' ten times, resulting in the string '5555555555'. The print() function then outputs this concatenated string without quotes.

Exam trap

The trap here is that candidates often confuse the string repetition operator with arithmetic multiplication, leading them to mistakenly compute 10 * 5 = 50 instead of recognizing that the operand is a string literal.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes the result is the integer 10, ignoring that the string '5' is repeated, not converted to an integer. Option B is wrong because it treats the string '5' as the integer 5 and performs arithmetic multiplication (10 * 5 = 50), which is a common confusion between string repetition and numeric multiplication. Option C is wrong because it suggests only a single '5' is output, misunderstanding that the operator repeats the string multiple times.

281
MCQmedium

A developer writes: print('Hello' + 5). What is the result?

A.Hello 5
B.TypeError
C.SyntaxError
D.Hello5
AnswerB

Cannot concatenate str and int.

Why this answer

In Python, the + operator performs string concatenation only when both operands are strings. Attempting to concatenate a string ('Hello') with an integer (5) raises a TypeError because Python does not implicitly convert the integer to a string for concatenation. This is a fundamental type safety feature of the language.

Exam trap

This exact scenario tests whether candidates understand that Python does not implicitly convert an integer to a string for concatenation, unlike loosely-typed languages.

How to eliminate wrong answers

Option A is wrong because it suggests that Python would automatically insert a space between the string and integer, which is not the case; the + operator does not add spaces. Option C is wrong because the code is syntactically valid (no missing colons, parentheses, or keywords) — the error occurs at runtime, not during parsing. Option D is wrong because it implies Python would implicitly convert the integer 5 to the string '5' and concatenate, but Python's strict type system prevents this without an explicit str() call.

282
MCQhard

What is the output of the following code? numbers = [1, 2, 3, 4, 5] total = 0 for i in numbers: if i % 2 == 0: continue total += i print(total)

A.10
B.8
C.6
D.9
AnswerD

Correct; index 2 is 9.

Why this answer

The exhibit shows code that iterates over the list [1, 2, 3, 4, 5] and uses `if i % 2 == 0: continue` to skip even numbers. Only odd numbers (1, 3, 5) are summed, giving 1 + 3 + 5 = 9. Therefore, option D is correct.

Exam trap

Python Institute often tests the `continue` statement by embedding it inside a conditional that filters out specific values, leading candidates to mistakenly sum all elements or incorrectly include the skipped values.

How to eliminate wrong answers

Option A is wrong because 10 would be the sum of all numbers in the list (1+2+3+4+5), but the `continue` statement skips even numbers, so not all numbers are added. Option B is wrong because 8 would be the sum if only the number 2 was skipped (1+3+4+5=13) or if a different condition was used, but the code skips both 2 and 4. Option C is wrong because 6 would be the sum of only the even numbers (2+4), but the code adds odd numbers, not even numbers.

283
MCQmedium

Which of the following best describes the behavior of the 'range' function in a for loop?

A.It generates a sequence of numbers from start to stop exclusive
B.It returns a list of numbers with a default step of 0
C.It can only be used with integers
D.It generates a list of numbers from start to stop inclusive
AnswerA

Correct: stop is not included.

Why this answer

The built-in `range()` function in Python generates an immutable sequence of numbers from the start value (default 0) up to, but not including, the stop value. When used in a `for` loop, it yields each number in the sequence one at a time, making it ideal for iterating a fixed number of times. The stop value is exclusive, meaning the loop body does not execute for the stop value itself.

Exam trap

Python Institute often tests the misconception that `range()` returns a list or that the stop value is inclusive, leading candidates to pick option D, but in Python, `range()` returns a lazy sequence and the stop value is always exclusive.

How to eliminate wrong answers

Option B is wrong because the default step of `range()` is 1, not 0; a step of 0 would cause a `ValueError`. Option C is wrong because `range()` can accept integer arguments only, but it can also be used with negative integers and zero, and the step can be negative; however, it strictly requires integers, not floats. Option D is wrong because `range()` generates numbers from start to stop exclusive, not inclusive; the stop value is never included in the sequence.

284
Multi-Selectmedium

Which two of the following statements about Python lists are true?

Select 2 answers
A.Lists are immutable.
B.List elements can be accessed using negative indices.
C.The append() method inserts an element at the beginning of the list.
D.The len() function returns the number of elements in a list.
E.Lists can only contain elements of the same data type.
AnswersB, D

Negative indices start from -1 for the last element.

Why this answer

Python lists support negative indexing, where -1 refers to the last element, -2 to the second last, and so on. This allows convenient access to elements from the end of the list without needing to calculate the length.

Exam trap

Python Institute often tests the misconception that lists are immutable (confusing them with tuples) or that append() inserts at the beginning (confusing it with insert(0, ...)), and candidates may also incorrectly assume lists are homogeneous like arrays in some other languages.

285
MCQhard

A programmer wants to create a function that can accept any number of keyword arguments and store them in a dictionary. Which function definition is correct?

A.def func(kwargs):
B.def func(**kwargs):
C.def func(**args):
D.def func(*kwargs):
AnswerB

Correct: **kwargs accepts arbitrary keyword arguments.

Why this answer

The **kwargs parameter in a function definition collects any number of extra keyword arguments into a dictionary. The double asterisk (**) is the Python syntax for capturing keyword arguments, and 'kwargs' is the conventional name for the resulting dictionary.

Exam trap

The PCEP exam often tests the distinction between *args (positional arguments packed into a tuple) and **kwargs (keyword arguments packed into a dictionary), and the trap here is that candidates confuse the single asterisk for keyword arguments or forget that the double asterisk is required for dictionary packing.

How to eliminate wrong answers

Option A is wrong because 'kwargs' without the double asterisk is just a regular parameter name; it does not collect keyword arguments and will cause a TypeError if keyword arguments are passed. Option C is wrong because '**args' uses the conventional name for positional arguments ('args') with the keyword argument syntax, which is misleading and non-standard, though technically it would work; however, the exam expects the conventional **kwargs. Option D is wrong because '*kwargs' uses a single asterisk, which collects extra positional arguments into a tuple, not keyword arguments into a dictionary.

286
MCQhard

Refer to the exhibit. What is printed?

A.None
B.x greater
C.equal
D.y greater
AnswerB

The if condition is satisfied.

Why this answer

The code defines x = 10 and y = 5. The if-elif-else structure first checks if x > y, which is true (10 > 5), so it prints 'x greater' and skips the remaining conditions. Therefore, option B is correct.

Exam trap

The PCEP exam often tests the sequential evaluation of if-elif-else chains, where candidates mistakenly think multiple branches can execute or that the else branch runs when a prior condition is true.

How to eliminate wrong answers

Option A is wrong because the code does not produce None; it prints a string. Option C is wrong because x is not equal to y (10 != 5), so the elif condition x == y is false. Option D is wrong because the first condition x > y is true, so the else branch (which would print 'y greater') is never executed.

287
Multi-Selecthard

Which THREE of the following are built-in Python data types? (Choose three.)

Select 3 answers
A.str
B.boolean
C.int
D.list
E.array
AnswersA, C, D

Built-in: string type.

Why this answer

`str` is a built-in Python data type used to represent sequences of Unicode characters. It is one of the fundamental immutable sequence types in Python, defined in the language specification and available without importing any module.

Exam trap

Python Institute often tests the distinction between built-in types and types available only through modules, so candidates mistakenly choose `array` or `boolean` because they sound familiar, but Python uses `bool` and requires importing `array`.

288
MCQhard

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

A.Prints 10.5
B.Prints 10
C.Raises TypeError
D.Raises ValueError
AnswerD

int() expects integer representation.

Why this answer

The code attempts to convert the string '10.5' to an integer using int(). Since '10.5' contains a decimal point, it is not a valid integer literal; int() cannot parse it and raises a ValueError. The correct approach would be to first convert to float (float('10.5')) and then to int if needed.

Exam trap

Python Institute often tests the distinction between ValueError and TypeError, trapping candidates who think a decimal string causes a TypeError when it actually raises a ValueError because the string is not a valid integer literal.

How to eliminate wrong answers

Option A is wrong because the code does not print 10.5; int('10.5') raises an exception before any print occurs. Option B is wrong because int('10.5') does not truncate or round the string to 10; it raises a ValueError instead. Option C is wrong because TypeError occurs when an operation is applied to an inappropriate type (e.g., adding string and int), but here the issue is that the string '10.5' is not a valid integer representation, which is a ValueError.

289
MCQeasy

A student writes the following code to calculate the average of two numbers: ```python num1 = input("Enter first number: ") num2 = input("Enter second number: ") avg = (num1 + num2) / 2 print("Average:", avg) ``` When executed, the code raises a TypeError. What is the most likely cause?

A.The division operator '/' is not allowed for integers
B.The input() function returns a string, not a number, so arithmetic operations are invalid without conversion
C.The addition operator '+' cannot be used with strings
D.The variable names num1 and num2 are reserved keywords
AnswerB

Correct. input() returns a string; arithmetic requires numeric conversion.

Why this answer

The `input()` function in Python always returns a string, regardless of what the user types. Attempting to use the `+` operator on two strings performs concatenation, not numeric addition, and then dividing a concatenated string by an integer with `/` raises a `TypeError` because the `/` operator is not defined for strings. To fix this, the inputs must be explicitly converted to numbers using `int()` or `float()` before arithmetic operations.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type when the user types digits, leading candidates to overlook the need for explicit type conversion with `int()` or `float()`.

How to eliminate wrong answers

Option A is wrong because the division operator '/' is fully allowed for integers in Python and performs true division, returning a float. Option C is wrong because the addition operator '+' can be used with strings for concatenation; the error arises from the subsequent division, not the addition itself. Option D is wrong because 'num1' and 'num2' are not reserved keywords in Python; they are valid variable names.

290
MCQeasy

A developer writes the following code: x = 5; y = x; x = 10. What are the values of x and y after execution?

A.x = 10, y = 5
B.x = 5, y = 10
C.x = 5, y = 5
D.x = 10, y = 10
AnswerA

x is reassigned to 10, y still holds the original 5

Why this answer

In Python, integers are immutable, and the assignment `y = x` copies the reference to the integer object 5, not the variable itself. When `x = 10` is executed, it binds the name `x` to a new integer object 10, while `y` still references the original object 5. Thus, after execution, `x` is 10 and `y` is 5.

Exam trap

Python Institute often tests the misconception that `y = x` creates a persistent link between variables, leading candidates to incorrectly assume `y` changes when `x` is reassigned.

How to eliminate wrong answers

Option B is wrong because it suggests `x = 5` and `y = 10`, which would require `y` to be reassigned after `x` changed, but no such reassignment occurs. Option C is wrong because it implies `x` remains 5, ignoring the explicit reassignment `x = 10`. Option D is wrong because it assumes `y` is updated when `x` changes, which would only happen if integers were mutable or if `y` were a reference to `x` itself, but Python integers are immutable and assignment creates a new binding.

291
MCQhard

A Python script processes a large file and runs out of memory. Which solution is most appropriate?

A.Increase the memory allocation
B.Use a while loop to read chunks
C.Read the entire file into memory and split
D.Process the file line by line using a for loop
AnswerD

This reads each line as needed, keeping memory usage low.

Why this answer

Reading a file line by line with a for loop in Python processes one line at a time, keeping only the current line in memory. This avoids loading the entire file into RAM, which is the root cause of the memory exhaustion when dealing with large files.

Exam trap

The PCEP exam often tests the misconception that reading a file in chunks with a while loop is the best approach, when in fact the idiomatic for loop over the file object is simpler, safer, and the recommended pattern in Python for line-by-line processing.

How to eliminate wrong answers

Option A is wrong because simply increasing memory allocation does not solve the underlying inefficiency; it only postpones the problem and may not be feasible or cost-effective. Option B is wrong because using a while loop to read chunks (e.g., file.read(chunk_size)) still requires manual buffer management and can still lead to memory issues if chunks are too large or not handled properly; the idiomatic Python approach is to iterate over the file object directly. Option C is wrong because reading the entire file into memory and then splitting it is exactly the behavior that causes memory exhaustion; it defeats the purpose of processing a large file.

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

293
Multi-Selecthard

Which TWO of the following expressions evaluate to 0? (Select two.)

Select 2 answers
A.False * 1
B.5 // 2 * 2
C.True == 0
D.int(0.5)
E.5 % 2
AnswersA, D

False is 0, product is 0.

Why this answer

In Python, `False` is treated as 0 in arithmetic contexts, so `False * 1` evaluates to `0 * 1 = 0`. Option D is correct because `int(0.5)` truncates the decimal part toward zero, resulting in the integer 0.

Exam trap

Python Institute often tests the distinction between boolean values in arithmetic versus comparison contexts, tricking candidates into thinking `True == 0` evaluates to the integer 0 rather than the boolean `False`.

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

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

296
MCQeasy

A program prompts a user for their age using input(). Which line of code correctly stores the age as an integer?

A.age = str(input("Enter age: "))
B.age = float(input("Enter age: "))
C.age = int(input("Enter age: "))
D.age = input("Enter age: ")
AnswerC

Correctly converts input string to integer.

Why this answer

The `int()` function explicitly converts the string returned by `input()` into an integer, which is required for storing a numeric age value. The `input()` function always returns a string in Python, so without conversion, arithmetic operations would fail or produce unexpected results.

Exam trap

The trap here is that candidates often forget `input()` returns a string and assume the user's typed digits are automatically stored as a number, leading them to pick option D without any conversion.

How to eliminate wrong answers

Option A is wrong because `str()` converts the input to a string, but `input()` already returns a string, so this adds unnecessary conversion and does not produce an integer. Option B is wrong because `float()` converts the input to a floating-point number, which is not appropriate for an age that should be a whole number and may introduce decimal precision issues. Option D is wrong because it stores the raw string from `input()` without any type conversion, so the variable remains a string and cannot be used directly in integer arithmetic.

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

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

299
MCQhard

A data analyst writes a Python script to double each element in a matrix without altering the original. The code is: original = [[1,2,3],[4,5,6]] copy = original for i in range(len(original)): for j in range(len(original[i])): copy[i][j] *= 2 print(original) The output shows [[2,4,6],[8,10,12]], meaning the original was also changed. Which single modification to the line 'copy = original' ensures the original matrix remains unchanged?

A.Replace `copy = original` with `copy = original[:]`
B.Replace `copy = original` with `import copy; copy = copy.deepcopy(original)`
C.Replace `copy = original` with `copy = list(original)`
D.Replace the nested loop with a list comprehension: `copy = [[x*2 for x in row] for row in original]`
AnswerB

deepcopy creates independent copies of all nested objects.

Why this answer

`copy.deepcopy()` creates a fully independent copy of the nested list structure. In Python, assignment (`copy = original`) only copies the reference to the outer list, so modifying elements through `copy` also modifies `original`. Shallow copies (like `original[:]` or `list(original)`) copy the outer list but still share references to the inner lists, so changes to inner elements affect both.

Only `deepcopy` recursively duplicates all nested objects, ensuring the original matrix remains unchanged.

Exam trap

Python Institute often tests the distinction between shallow and deep copy in nested structures, and the trap here is that candidates assume `original[:]` or `list(original)` create a full independent copy, not realizing that inner lists are still shared references.

How to eliminate wrong answers

Option A is wrong because `original[:]` creates a shallow copy of the outer list; the inner lists are still shared references, so modifying `copy[i][j]` still alters `original[i][j]`. Option C is wrong because `list(original)` also performs a shallow copy, producing a new outer list but reusing the same inner list objects, so the original matrix is still mutated. Option D is wrong because it replaces the entire loop with a list comprehension that builds a new matrix without modifying `original`, but the question asks for a modification to the line `copy = original`, not to the loop; this option changes the loop structure, not the assignment, and thus does not satisfy the requirement.

300
MCQhard

What is the output of the following code? config = {} print('Not set' if config.get('timeout') is None else config.get('timeout'))

A.KeyError: 'timeout'
B.Not set
C.None
D.False
AnswerB

The .get() method returns None for missing key, so the condition is True, outputting 'Not set'.

Why this answer

The code attempts to access a dictionary key 'timeout' that does not exist. Using square bracket access on a missing key raises a KeyError, but the code uses the .get() method, which returns None by default if the key is missing. Since the key 'timeout' is not in the dictionary, .get('timeout') returns None, and the print statement outputs 'Not set' because the condition `config.get('timeout') is None` evaluates to True.

Exam trap

Python Institute often tests the distinction between dict[key] (which raises KeyError) and dict.get(key) (which returns None) to trap candidates who assume all dictionary access methods behave the same way.

How to eliminate wrong answers

Option A is wrong because a KeyError would only occur if square brackets (config['timeout']) were used on a missing key, but the code uses .get() which safely returns None. Option C is wrong because None is the actual return value of .get(), but the code prints the string 'Not set' due to the if condition, not None itself. Option D is wrong because False is a boolean value, not the output; the condition checks for None, not False, and prints a string.

Page 3

Page 4 of 7

Page 5

All pages