Courseiva

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

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

Page 2

Page 3 of 7

Page 4
151
MCQhard

You are a developer for a financial application that processes transactions. The application uses a dictionary to store account balances where keys are account numbers (strings) and values are floats. A function `transfer(from_acc, to_acc, amount)` is supposed to subtract amount from `from_acc` and add it to `to_acc`. However, some transfers are resulting in incorrect balances: the `from_acc` balance is reduced but the `to_acc` balance is not increased. The code uses `try-except` to catch KeyError if an account does not exist. Upon inspection, the function first checks if both accounts exist, then performs subtraction, then addition, and finally returns success. No exceptions are raised during the problematic transfers. The accounts definitely exist. What is the most likely cause?

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

Race condition can cause the second update to be lost.

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

152
MCQeasy

A beginner Python learner writes a script to swap two numbers: a = 10 b = 20 a = b b = a print("a =", a, "b =", b) The output is "a = 20 b = 20". The learner expected "a = 20 b = 10". Which of the following is the most Pythonic way to fix the code?

A.Use bitwise XOR: a ^= b; b ^= a; a ^= b
B.Use tuple unpacking: a, b = b, a
C.Use a temporary variable: temp = a; a = b; b = temp
D.Use integer arithmetic: a = a + b; b = a - b; a = a - b
AnswerB

This is the standard Pythonic swap.

Why this answer

Tuple unpacking is the most Pythonic and idiomatic way to swap two variables. It leverages Python's ability to evaluate the right-hand side as a tuple before assignment, so the original values of `a` and `b` are captured simultaneously, avoiding the overwrite issue in the original code.

Exam trap

Python Institute often tests the misconception that any working swap is equally Pythonic, but the PCEP emphasizes idiomatic Python (PEP 8 style), making tuple unpacking the only correct answer despite other options being functionally correct.

How to eliminate wrong answers

Option A is wrong because while bitwise XOR can swap integers, it is not Pythonic, less readable, and can fail with floating-point numbers or large integers due to Python's arbitrary precision. Option C is wrong because using a temporary variable is a valid but non-Pythonic approach; it works but is verbose and not the preferred style in Python. Option D is wrong because integer arithmetic can cause overflow in languages with fixed-width integers, but in Python it works; however, it is less readable and not idiomatic, making it non-Pythonic.

153
Multi-Selecteasy

Which TWO of the following are valid variable names in Python?

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

Valid: letters and underscore.

Why this answer

`total_sum` starts with a letter and contains only letters and underscores, which are allowed in Python identifiers. Python variable names must begin with a letter or underscore and can be followed by letters, digits, or underscores.

Exam trap

The PCEP exam often tests the rule that hyphens are invalid in variable names (tricking candidates who are used to languages like Lisp or CSS) and that keywords cannot be used as identifiers, even though they look like valid names.

154
MCQmedium

A program reverses a string using a while loop. The code is: text = "hello" reversed_text = "" index = len(text) - 1 while index > 0: reversed_text += text[index] index -= 1 print(reversed_text) It prints 'olle' instead of 'olleh'. What is the error?

A.Change the condition to 'while index >= 0:'
B.Change the initial index to len(text)
C.Use a for loop instead
D.Use string slicing: reversed_text = text[::-1]
AnswerA

This ensures index 0 is processed.

Why this answer

The while loop condition `index > 0` stops when `index` becomes 0, so the character at index 0 (the first character 'h') is never appended to `reversed_text`. Changing the condition to `while index >= 0:` ensures the loop runs for index values from 4 down to 0 inclusive, producing the full reversed string 'olleh'.

Exam trap

Python Institute often tests off-by-one errors in while loops, where candidates mistakenly think `index > 0` covers all elements because they forget that the first index is 0, not 1.

How to eliminate wrong answers

Option B is wrong because setting the initial index to `len(text)` would cause an IndexError on the first iteration (index 5 is out of range for a 5-character string). Option C is wrong because using a for loop is not necessary; the while loop logic is correct except for the off-by-one condition, so switching to a for loop does not fix the root cause. Option D is wrong because while string slicing `text[::-1]` is a valid alternative, the question asks for the error in the given while loop code, not for a different implementation.

155
MCQmedium

A weather station records temperature as a string '23.5'. The technician writes code to convert to Fahrenheit for a report. Which code will produce the correct Fahrenheit value without errors?

A.fahrenheit = float(celsius) * 9/5 + 32
B.fahrenheit = celsius * 9/5 + 32
C.fahrenheit = int(celsius) * 9/5 + 32
D.fahrenheit = (celsius + 32) * 9/5
AnswerA

Correctly converts to float and applies formula

Why this answer

It explicitly converts the string '23.5' to a float using the `float()` function, preserving the decimal part. The expression `float(celsius) * 9/5 + 32` then correctly applies the Fahrenheit conversion formula (F = C * 9/5 + 32) using floating-point arithmetic, which yields the precise result 74.3 without any type errors.

Exam trap

Python Institute often tests the distinction between `int()` and `float()` conversion, trapping candidates who forget that `int()` truncates the decimal part, leading to a loss of precision in calculations.

How to eliminate wrong answers

Option B is wrong because `celsius` is a string ('23.5'), and multiplying a string by a number causes a TypeError in Python (e.g., `'23.5' * 9` is invalid). Option C is wrong because `int(celsius)` truncates the decimal part, converting '23.5' to 23, which produces an incorrect Fahrenheit value (73.4 instead of 74.3). Option D is wrong because it uses the wrong formula: adding 32 before multiplying by 9/5 gives (23.5 + 32) * 9/5 = 99.9, which is not the correct conversion from Celsius to Fahrenheit.

156
MCQeasy

How many times will the following loop print 'Hi'? for i in range(3): print('Hi')

A.2
B.3
C.0
D.4
AnswerB

Correct number of iterations.

Why this answer

The loop `for i in range(3):` iterates exactly three times because `range(3)` generates the sequence 0, 1, 2. Each iteration executes `print('Hi')`, so 'Hi' is printed three times. Option B is correct.

Exam trap

Python Institute often tests the off-by-one misconception where candidates think `range(3)` includes 3, leading them to choose 4 iterations, or they mistakenly count from 1 instead of 0.

How to eliminate wrong answers

Option A is wrong because it suggests the loop runs only twice, which would be the case for `range(2)` or a loop with a different stop value. Option C is wrong because the loop always executes at least once when the stop value is positive; `range(3)` is not empty. Option D is wrong because `range(3)` stops before 3, producing exactly three values, not four.

157
MCQeasy

Which operator is used for integer division in Python?

A.%
B.**
C./
D.//
AnswerD

Correct; // performs floor division.

Why this answer

The // operator in Python performs floor division, which returns the integer quotient after dividing two numbers, discarding any fractional remainder. For example, 7 // 2 yields 3, not 3.5, making it the explicit integer division operator.

Exam trap

Python Institute often tests the distinction between / (true division returning a float) and // (floor division returning an integer), trapping candidates who assume / always performs integer division in Python as it does in some other languages.

How to eliminate wrong answers

Option A is wrong because % is the modulo operator, which returns the remainder of a division, not the quotient. Option B is wrong because ** is the exponentiation operator, used for raising a number to a power. Option C is wrong because / is the true division operator, which always returns a float result even if the operands are integers.

158
Matchingmedium

Match each Python keyword to its use.

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

Concepts
Matches

Starts a conditional statement

Starts a loop over a sequence

Starts a loop that repeats while a condition is true

Defines a function

Exits a function and optionally returns a value

Why these pairings

The correct matches are: break is used to exit a loop prematurely; continue skips the current iteration; pass is a no-operation statement. Common mistakes include swapping the definitions of break and continue.

159
MCQhard

Refer to the exhibit. Which of the following is true about the output?

A.Prints "Error:" then "Done" without the message
B.Raises an unhandled exception
C.Prints "Error: invalid literal for int() with base 10: 'abc'" then "Done"
D.Prints only "Done"
AnswerC

The error message is printed, then finally runs.

Why this answer

The code attempts to convert the string 'abc' to an integer using int('abc'), which raises a ValueError. The except block catches this exception and prints 'Error:' followed by the exception message, then the finally block always executes and prints 'Done'. Thus, the output is 'Error: invalid literal for int() with base 10: 'abc'' followed by 'Done'.

Exam trap

The PCEP exam often tests the misconception that the finally block suppresses or replaces the exception output, or that the except block does not print the exception message, leading candidates to overlook the explicit print of the error message before 'Done'.

How to eliminate wrong answers

Option A is wrong because it suggests the message is omitted, but the except block explicitly prints the exception message via the 'as e' clause. Option B is wrong because the exception is caught by the except block, so it is handled, not unhandled. Option D is wrong because the except block executes before the finally block, so 'Error: ...' is printed before 'Done', not only 'Done'.

160
MCQeasy

A developer writes a function that should return the sum of two numbers, but the code returns 0 instead. What is the most likely cause? def add(a, b): result = a + b print(add(3, 4))

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

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

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

161
MCQeasy

Given a list of names = ['Alice', 'Bob', 'Charlie'], a developer wants to create a dictionary mapping each name to its length. Which expression accomplishes this?

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

162
Multi-Selectmedium

Which THREE of the following expressions evaluate to True?

Select 3 answers
A.3 == int("3")
B."3" == 3
C.bool(1)
D.bool(0)
E.3 == 3.0
AnswersA, C, E

Correct. int('3') returns 3, so 3 == 3 is True.

Why this answer

The `int()` function converts the string `"3"` to the integer `3`, and the `==` operator compares the values, returning `True` since both sides are the integer `3`. Option C is correct because `bool(1)` returns `True` as any non-zero integer is considered truthy in Python. Option E is correct because Python's `==` operator performs value equality, and `3` (integer) and `3.0` (float) represent the same numeric value, so the comparison evaluates to `True`.

Note that the question asks for two correct answers, but based on the evaluations, options A, C, and E are all true. This might indicate an error in the question design.

Exam trap

Python Institute often tests the misconception that `==` performs type coercion for all types (like JavaScript), but in Python, `==` only coerces numeric types (int, float, complex) and returns `False` for cross-type comparisons like string vs int.

163
MCQmedium

What is the output of the following code? print(3 * 'ab' + 'c')

A.'abababc'
B.'ababc'
C.TypeError
D.'ababab c'
AnswerA

Correct result.

Why this answer

The expression `3 * 'ab' + 'c'` first multiplies the string `'ab'` by 3, resulting in `'ababab'` (string repetition), and then concatenates `'c'` using the `+` operator, producing `'abababc'`. In Python, the `*` operator on a string and an integer repeats the string that many times, and `+` concatenates strings.

Exam trap

Python Institute often tests the order of operations and the fact that `*` binds tighter than `+` in Python, leading candidates to mistakenly think the expression is evaluated as `3 * ('ab' + 'c')` or to forget that string repetition produces a single concatenated string without separators.

How to eliminate wrong answers

Option B is wrong because `'ababc'` would result from `2 * 'ab' + 'c'`, not from multiplying by 3. Option C is wrong because both operations are valid on strings in Python; no TypeError occurs. Option D is wrong because string concatenation does not insert a space; the output is `'abababc'` without any space before `'c'`.

164
MCQeasy

Refer to the exhibit. What is the output?

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

Correct slice.

Why this answer

The code creates a list [1,2,3] and uses slicing with start index 0 and end index 2 (exclusive), extracting elements at indices 0 and 1, which are 1 and 2. Therefore, the output is [1,2].

Exam trap

A common mistake is confusing slice indices with the values themselves or misapplying the stop index (exclusive). Candidates might think `[:2]` includes index 2, giving [1,2,3], or that it starts at index 1, giving [2,3].

How to eliminate wrong answers

Option A is wrong because it includes 3, but the condition `if i != 3` explicitly excludes 3 from being appended. Option B is wrong because it suggests the loop starts at 0, but the list contains 1, 2, 3, not indices. Option D is wrong because it omits 1 and includes 3, but the loop appends 1 and 2, and skips 3.

165
Multi-Selecteasy

Which TWO of the following are valid ways to comment in Python?

Select 2 answers
A.$ This is a comment
B.# This is a comment
C./* This is a comment */
D.// This is a comment
E.''' This is a comment '''
AnswersB, E

Standard single-line comment.

Why this answer

The hash symbol (#) is the standard syntax for single-line comments in Python. Everything after # on that line is ignored by the Python interpreter, making it a valid comment.

Exam trap

Python Institute often tests the distinction between Python's comment syntax and comment styles from other languages (e.g., //, /* */) to catch candidates who are familiar with C-family languages but new to Python.

166
Matchingmedium

Match each exception type to its description.

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

Concepts
Matches

Raised when a function receives an argument of correct type but inappropriate value

Raised when an operation is applied to an object of inappropriate type

Raised when a sequence subscript is out of range

Raised when a mapping key is not found in a dictionary

Raised when division or modulo operation is performed with zero as divisor

Why these pairings

These are built-in exceptions in Python that indicate specific error conditions.

167
MCQeasy

A junior developer is writing a script to read a number from input and double it. They write: num = input("Enter a number: ") result = num * 2 print(result) When they test with input 5, the output is '55' instead of 10. What is wrong?

A.There is a syntax error in the multiplication line.
B.The print function is incorrectly formatting the output.
C.The variable name 'num' conflicts with a built-in function.
D.The input is treated as a string; they need to convert it to int.
AnswerD

input() returns a string; string * 2 duplicates the string.

Why this answer

The `input()` function in Python always returns a string, even if the user types a number. When you use the `*` operator on a string, it repeats the string, so `'5' * 2` yields `'55'`. To perform numeric multiplication, you must convert the input to an integer using `int(input(...))`.

Exam trap

The trap here is that candidates often assume `input()` returns a number because the user typed digits, but Python treats all keyboard input as a string, and the `*` operator's string repetition behavior is a classic PCEP trick.

How to eliminate wrong answers

Option A is wrong because there is no syntax error; the line `result = num * 2` is syntactically valid Python. Option B is wrong because the `print()` function is correctly outputting the value of `result`; the issue is the value itself, not the formatting. Option C is wrong because `num` is not a built-in function name; built-in functions like `int`, `float`, `str` are reserved, but `num` is a free variable name.

168
Multi-Selecteasy

Which TWO of the following expressions produce the integer 5?

Select 2 answers
A."5"
B.10 // 2
C.int(5.7)
D.5.0
E.10 / 2
AnswersB, C

Floor division returns integer 5.

Why this answer

`10 // 2`, uses floor division in Python, which divides 10 by 2 and returns the integer quotient 5, discarding any fractional remainder. Option C, `int(5.7)`, truncates the decimal part of the float 5.7, converting it directly to the integer 5. Both expressions produce the exact integer value 5.

Exam trap

Python Institute often tests the distinction between `/` (true division returning float) and `//` (floor division returning int), as well as the difference between numeric types (int vs. float vs. string), to catch candidates who overlook Python's implicit type conversions.

169
Multi-Selecteasy

Which TWO of the following are valid Python variable names?

Select 2 answers
A.my_var2
B.2nd_var
C._myvar
D.my-var
E.for
AnswersA, C

Letters, underscores, and digits are allowed.

Why this answer

Python variable names must start with a letter or underscore, and can contain letters, digits, and underscores. 'my_var2' starts with a letter and contains only valid characters, so it is a valid identifier.

Exam trap

The PCEP exam often tests the rule that variable names cannot start with a digit, and the distinction between hyphens (which are operators) and underscores (which are valid identifier characters), leading candidates to mistakenly accept '2nd_var' or 'my-var' as valid.

170
Multi-Selecteasy

Which TWO of the following are valid ways to determine if a variable 'x' is an integer? (Select two.)

Select 2 answers
A.type(x) == int
B.x.isint()
C.x.__class__ == int
D.isinstance(x, int)
E.int(x) == x
AnswersA, D

Valid; compares type.

Why this answer

The `type()` function returns the type of the object, and comparing it directly to `int` checks if the variable is exactly an integer. This is a straightforward and reliable way to test the type in Python.

Exam trap

The PCEP exam often tests the distinction between type-checking methods and the misconception that `int(x) == x` is a valid type check, when in fact it only checks value equality after conversion and can produce false positives with floats or raise errors with non-numeric types.

171
Multi-Selecteasy

Which TWO of the following are valid variable names in Python?

Select 2 answers
A._myVar
B.my Var
C.my-var
D.my_var
E.2ndPlace
AnswersA, D

_myVar is valid: it starts with an underscore and contains only letters and underscores.

Why this answer

Options A (_myVar) and D (my_var) are the two correct variable names. Option B (my Var) is invalid because it contains a space, option C (my-var) contains a hyphen which is not allowed, and option E (2ndPlace) starts with a digit.

Exam trap

The PCEP exam often tests the rule that hyphens are invalid in variable names, as candidates may confuse them with underscores or assume they are allowed like in other languages (e.g., Lisp or some shell scripting).

172
MCQmedium

A developer wants to read a floating-point number from user input and compute its square. Which code snippet correctly accomplishes this?

A.num = input(); result = num * num
B.num = float(input()); result = num ** 2
C.result = input() ** 2
D.num = int(input()); result = num ** 2
AnswerB

Correct: converts input to float.

Why this answer

It uses `float(input())` to convert the user's input (which is always a string) into a floating-point number, and then computes the square using the exponentiation operator `**`. This ensures that decimal values are handled correctly, which is required for computing the square of a floating-point number.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type, leading candidates to forget explicit conversion and choose options that attempt arithmetic on strings.

How to eliminate wrong answers

Option A is wrong because `input()` returns a string, and multiplying two strings with `*` performs string repetition, not numeric multiplication, so it will not compute the square of a number. Option C is wrong because `input()` returns a string, and the `**` operator cannot be applied to a string; this will raise a TypeError. Option D is wrong because `int(input())` converts the input to an integer, which truncates any decimal part, so it cannot correctly handle floating-point numbers as required.

173
Multi-Selectmedium

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

Select 2 answers
A.1 == True
B.0 == False
C.'0' == 0
D.2 == True
E.None == False
AnswersA, B

True: 1 equals True.

Why this answer

In Python, the boolean value `True` is equal to the integer `1` due to the fact that `bool` is a subclass of `int`, and `True` is internally represented as `1`. The comparison `1 == True` evaluates to `True` because Python performs implicit type coercion, converting `True` to `1` before the equality check.

Exam trap

Python Institute often tests the misconception that `True` and `False` are completely separate from integers, leading candidates to incorrectly reject options A and B, or to mistakenly believe that `'0'` or `None` are falsy enough to equal `0` or `False`.

174
MCQmedium

A function is defined as: def add(a, b=5): return a + b What is the result of add(10)?

A.10
B.5
C.15
D.Error
AnswerC

Uses default b=5.

Why this answer

The function `add(a, b=5)` defines a default value of 5 for parameter `b`. When called as `add(10)`, the argument 10 is assigned to `a`, and `b` uses its default value of 5. The function returns `10 + 5 = 15`, making option C correct.

Exam trap

Python Institute often tests the misconception that default parameters are required or that omitting them causes an error, leading candidates to pick 'Error' (option D) when the function is actually called correctly with a single argument.

How to eliminate wrong answers

Option A is wrong because it assumes `b` is ignored or defaults to 0, but the default is 5, so the result is not 10. Option B is wrong because it suggests the function returns only the default value of `b`, ignoring the argument `a=10`. Option D is wrong because the function call `add(10)` provides exactly one required argument (`a`), and `b` has a default value, so no error occurs.

175
Multi-Selectmedium

Which TWO of the following are valid Python variable names?

Select 2 answers
A._name
B.2name
C.name$
D.name-2
E.name_2
AnswersA, E

Valid. Starts with underscore.

Why this answer

Python variable names must start with a letter or an underscore, and '_name' begins with an underscore, which is allowed. The rest of the name consists of letters and underscores, making it a valid identifier per Python's naming rules.

Exam trap

Python Institute often tests the misconception that special characters like '$' or hyphens are allowed in variable names, or that names can start with digits, confusing Python's rules with those of other languages like JavaScript or shell scripting.

176
MCQmedium

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

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

Correct: Multiple return values without brackets form a tuple.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

177
MCQeasy

A junior developer needs to write code that processes a list of student scores and stops processing when a score of 100 is encountered, as that score represents a perfect score that should be treated separately. Which loop construct is most appropriate?

A.for score in scores: if score == 100: pass ...
B.for score in scores: if score == 100: break ... further processing
C.for i in range(len(scores)): if scores[i] == 100: exit() ...
D.while scores: score = scores.pop(); if score == 100: continue ...
AnswerB

Correct; break stops the loop.

Why this answer

The `break` statement immediately exits the loop when a score of 100 is encountered, which matches the requirement to stop processing further scores. The `for` loop iterates over the list naturally, and the `if` condition checks for the perfect score, making this the most straightforward and efficient construct for this scenario.

Exam trap

Python Institute often tests the distinction between `break`, `continue`, and `pass` in loops, and the trap here is that candidates may confuse `continue` (which skips only the current iteration) with `break` (which exits the loop entirely), leading them to choose option D incorrectly.

How to eliminate wrong answers

Option A is wrong because `pass` is a no-op statement that does nothing; it would skip the 100 but continue processing subsequent scores, failing to stop the loop. Option C is wrong because `exit()` terminates the entire program, not just the loop, which is overly drastic and not appropriate for simply stopping score processing. Option D is wrong because `continue` skips the current iteration and moves to the next, but it does not stop the loop; also, using `pop()` modifies the list destructively, which is not required and can lead to unintended side effects.

178
MCQmedium

After 'x = 5; x += 3', what is the value of x?

A.5
B.8
C.3
D.15
AnswerB

5 + 3 = 8.

Why this answer

The compound assignment operator `+=` adds the right operand to the current value of the variable and assigns the result back. Starting with `x = 5`, the statement `x += 3` is equivalent to `x = x + 3`, which computes `5 + 3 = 8` and stores it in `x`.

Exam trap

The trap here is that candidates often confuse `+=` with simple assignment or with other operators like `*=` or `=`, leading them to pick the original value, the right operand alone, or a product instead of the sum.

How to eliminate wrong answers

Option A is wrong because it suggests the value remains 5, ignoring that `+=` performs an addition and reassignment. Option C is wrong because it incorrectly treats `+=` as a simple assignment of the right operand (3) rather than an addition operation. Option D is wrong because it implies multiplication (5 * 3 = 15), confusing `+=` with `*=` or another operator.

179
Drag & Dropmedium

Arrange the steps to install a third-party Python package using pip.

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

Installing packages with pip involves checking pip, running install, and verifying.

180
MCQmedium

A company uses a for loop to iterate over a list of transaction amounts. They want to skip negative amounts. Which statement inside the loop correctly achieves this?

A.if amount < 0: amounts.remove(amount)
B.if amount < 0: break
C.if amount < 0: pass
D.if amount < 0: continue
AnswerD

Correct: continue skips the current iteration for negative amounts.

Why this answer

The `continue` statement immediately jumps to the next iteration of the loop, skipping any remaining code in the current iteration. When `amount < 0`, the loop will not process that negative transaction and will move to the next element in the list, effectively skipping negative amounts.

Exam trap

Python Institute often tests the distinction between `break`, `continue`, and `pass`, and the trap here is that candidates confuse `break` (which exits the loop) with `continue` (which skips to the next iteration), or think `pass` is a valid way to skip code when it actually does nothing.

How to eliminate wrong answers

Option A is wrong because `amounts.remove(amount)` modifies the list while iterating over it, which can lead to skipped elements or index errors due to the list's size changing during iteration. Option B is wrong because `break` terminates the entire loop prematurely, stopping all further iteration even for positive amounts after the first negative one. Option C is wrong because `pass` is a no-op that does nothing; it simply continues execution to the next line, so negative amounts would still be processed.

181
Multi-Selectmedium

Which THREE of the following are valid ways to create a list with elements 10, 20, 30?

Select 3 answers
A.my_list = [x for x in (10,20,30)]
B.my_list = list((10, 20, 30))
C.my_list = list(10, 20, 30)
D.my_list = [10; 20; 30]
E.my_list = [10, 20, 30]
AnswersA, B, E

Correct. List comprehension creates a list from the tuple elements.

Why this answer

Options A, B, and E are all valid ways to create a list with the elements 10, 20, 30. Option A uses a list comprehension to iterate over a tuple and produce the list. Option B uses the list() constructor with a tuple as the single iterable argument.

Option E is the most direct way: a list literal. Options C and D are invalid: C because list() requires a single iterable, not multiple positional arguments; D because Python list elements must be separated by commas, not semicolons.

Exam trap

In multi-select questions, carefully evaluate each option against the stem without reading in extra constraints. The question simply asks for valid ways to create a specific list; do not assume that a literal assignment is excluded unless explicitly stated. Be cautious about the number of correct answers: ensure you select all that apply, especially when the stem specifies a count.

182
MCQeasy

You are a junior developer at a small startup. Your team has a Python script that automates daily data processing. The script reads a CSV file, processes each row, and writes results to a new file. Recently, the script started crashing with a 'ValueError: invalid literal for int()' error. The error occurs on a line that converts a field to an integer using int() on a string value. The CSV file comes from an external source that sometimes contains non-numeric values like 'N/A' or empty strings. Which course of action is best to handle this robustly without stopping the entire process?

A.Wrap the conversion in a try-except block and handle the exception appropriately for each row.
B.Add logging before the conversion to print the problematic value.
C.Use a regex to replace all non-digit characters before conversion.
D.Contact the external source to ensure no missing values are sent.
AnswerA

Exception handling allows the script to continue processing other rows.

Why this answer

Wrapping the conversion in a try-except block allows the script to catch the ValueError for each row individually, log or handle the problematic row (e.g., skip it or use a default value), and continue processing the remaining rows without crashing. This is the standard Pythonic approach for handling expected but unpredictable data quality issues in external input, as it separates error handling from the main logic and preserves the robustness of the batch process.

Exam trap

The PCEP exam often tests the misconception that logging or pre-processing (like regex) is sufficient to prevent runtime errors, when in fact only exception handling can gracefully recover from an exception that has already been raised.

How to eliminate wrong answers

Option B is wrong because adding logging before the conversion only prints the problematic value but does not prevent the ValueError from being raised, so the script will still crash on the first invalid row. Option C is wrong because using a regex to replace all non-digit characters (e.g., removing 'N/A' entirely) could silently corrupt data (e.g., turning '123-456' into '123456' or removing valid negative signs) and does not handle empty strings or other non-numeric formats robustly. Option D is wrong because contacting the external source is a long-term process improvement, not an immediate fix; it does not handle the current crashing script and assumes the source can always provide clean data, which is unrealistic in production.

183
MCQeasy

You are maintaining a Python script that calculates team bonuses based on sales data. The script reads a dictionary where keys are employee names and values are total sales (float). It then applies a 10% bonus if sales exceed 5000. The code snippet is: def calculate_bonus(sales): for name, value in sales.items(): if value > 5000: print(f"{name} gets bonus") However, the manager wants the script to return a list of employees who qualify, not just print them. They also want to avoid side effects. What is the best way to modify this function?

A.Create a global list variable at the top of the script and append each qualifying name to it.
B.Keep the function as is and have the caller capture the printed names by redirecting stdout.
C.Use the dictionary's update method to mark bonus status in the original sales dictionary.
D.Build a list inside the function and return it at the end.
AnswerD

Returning a new list keeps the function pure and reusable.

Why this answer

It modifies the function to build a list of qualifying employee names inside the function and returns that list. This avoids side effects (no global variables, no mutation of the input dictionary) and follows the principle of returning results rather than printing them, making the function reusable and testable.

Exam trap

The PCEP exam often tests the concept of side effects versus pure functions, and the trap here is that candidates may think mutating the input dictionary (Option C) or using a global variable (Option A) are acceptable, when in fact they violate the principle of avoiding side effects and reduce code maintainability.

How to eliminate wrong answers

Option A is wrong because using a global list introduces side effects and makes the function non-reentrant and harder to debug; it also violates the principle of avoiding global state. Option B is wrong because capturing stdout is a fragile workaround that does not actually return data and still relies on the function's side effect of printing; it also adds unnecessary complexity and breaks if output is redirected. Option C is wrong because using the dictionary's update method to mark bonus status mutates the original sales dictionary, which is a side effect that can cause unexpected behavior in other parts of the script and violates the requirement to avoid side effects.

184
MCQhard

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

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

Why this answer

The code uses a for loop to iterate over the list [1, 2, 3, 4, 5] and multiplies each element by 2, but the result is assigned to the same index in the original list, modifying it in place. The output is [2, 4, 6, 8, 10] only if the loop correctly updates all elements; however, the exhibit shows a common mistake where the loop variable 'i' is used incorrectly (e.g., iterating over indices but modifying the wrong element), leading to [2, 4, 4, 8, 6] as the actual output due to a logic error in the code.

Exam trap

PCEP often tests the distinction between iterating over list elements directly (for x in lst) versus iterating over indices (for i in range(len(lst))), and the trap here is that candidates assume the loop doubles every element correctly without checking for off-by-one or assignment errors in the code.

How to eliminate wrong answers

Option A is wrong because it shows the original list unchanged, which would only happen if the loop did not modify the list or if the modifications were not applied. Option C is wrong because it represents the correct expected output if each element were doubled correctly, but the exhibit's code contains a bug that prevents this result. Option D is wrong because it shows an inconsistent pattern (e.g., 1 unchanged, 4 doubled, 3 unchanged, 8 doubled, 5 unchanged) that does not match the actual bug in the code.

185
Matchingmedium

Match each Python data type to its description.

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

Concepts
Matches

Whole numbers, e.g., 42

Numbers with decimal point, e.g., 3.14

Sequence of characters, e.g., 'hello'

Logical values True or False

Ordered, mutable collection of items

Why these pairings

The correct matches are: A (int - whole numbers), B (float - numbers with decimal point), D (bool - Boolean values True or False). Option C (str) is incorrect because strings are immutable sequences of characters, not mutable collections. Option E (list) is incorrect because lists are mutable collections, not immutable sequences.

Option F (tuple) is incorrect because tuples are immutable sequences, not mutable collections.

186
Matchingmedium

Match each Python function to its description.

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

Concepts
Matches

Outputs objects to the console

Reads a string from standard input

Returns the number of items in a container

Returns the type of an object

Converts a value to an integer

Why these pairings

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

187
MCQmedium

What is the output of the code in the exhibit?

A.Greater\nLess or equal
B.SyntaxError
C.Less or equal
D.Greater
AnswerC

The condition is false, so the else block executes and prints 'Less or equal'.

Why this answer

The code assigns x=10 and y=20 (assuming the exhibit shows these values), then checks if x > y. Since 10 > 20 is False, the if block does not execute, and the else block prints 'Less or equal'. Therefore, option C is correct.

Exam trap

A common pitfall: candidates may incorrectly assume the if block executes or forget that else runs when the condition is false, leading them to choose 'Greater' instead of correctly identifying the else output.

How to eliminate wrong answers

Option A is wrong because it suggests both branches execute, but Python's if-else structure ensures only one block runs based on the condition. Option B is wrong because the syntax is valid: comparison operators (>) and print() are correctly used, so no SyntaxError occurs. Option C is wrong because it is the actual output, not 'Greater', but the question asks for the correct answer, which is D (the output is 'Less or equal', not 'Greater').

188
MCQeasy

Which of the following expressions evaluates to False?

A.2 != 1
B.10 == 10
C.3 >= 4
D.5 < 10
AnswerC

3 is not >= 4, so false.

Why this answer

(3 >= 4) evaluates to False because the 'greater than or equal to' operator (>=) returns True only if the left operand is greater than or equal to the right operand. Since 3 is neither greater than nor equal to 4, the expression is False.

Exam trap

Python Institute often tests whether candidates confuse the direction of comparison operators (e.g., mistaking >= for <=) or forget that >= includes equality, leading them to incorrectly assume 3 >= 4 is True.

How to eliminate wrong answers

Option A is wrong because 2 != 1 uses the inequality operator (!=) and returns True since 2 is not equal to 1. Option B is wrong because 10 == 10 uses the equality operator (==) and returns True since both operands are equal. Option D is wrong because 5 < 10 uses the less-than operator (<) and returns True since 5 is indeed less than 10.

189
MCQmedium

A developer writes a function that returns multiple values as a tuple. Which of the following is a valid way to unpack the result into separate variables?

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

This is direct tuple unpacking.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

190
Multi-Selecthard

Which TWO operators in Python yield an integer result when applied to two integers?

Select 2 answers
A.//
B.**
C.%
D.*
E./
AnswersA, C

Floor division always returns an integer for ints.

Why this answer

The floor division operator (//) always returns an integer result when both operands are integers, discarding any fractional part. For example, 7 // 2 yields 3, not 3.5. This is because floor division performs integer division and truncates toward negative infinity, ensuring the result type is int when both inputs are int.

Exam trap

Python Institute often tests the distinction between / (always returns float) and // (returns int for int operands), and the trap here is that candidates mistakenly think the modulo operator (%) returns a float, but it actually returns an integer when both operands are integers, and they may also incorrectly believe that multiplication (*) always returns an integer (which it does, but the exam deliberately omits it from the correct answers to test knowledge of // and % specifically).

191
MCQeasy

A company maintains a list of employee names. They want to check if 'Alice' is in the list. Which of the following is the most Pythonic way to achieve this?

A.employees.contains('Alice')
B.for name in employees: if name == 'Alice': found = True; break
C.if employees.index('Alice') != -1:
D.if 'Alice' in employees:
AnswerD

Correct: the 'in' operator is concise and readable.

Why this answer

The most Pythonic way because it uses the `in` operator, which directly checks membership in a list with a single, readable expression. This approach is idiomatic Python, leveraging the language's built-in support for membership testing without manual iteration or exception handling.

Exam trap

Python Institute often tests the distinction between Python's `in` operator and methods from other languages (like `contains()`), or the incorrect assumption that `.index()` returns -1 on failure, which is a common trap for candidates coming from languages like Java or C++.

How to eliminate wrong answers

Option A is wrong because Python lists do not have a `contains()` method; this is a Java-style method name, not valid in Python. Option B is wrong because while the loop works, it is verbose and non-idiomatic; Python's `in` operator is the preferred, concise way to test membership. Option C is wrong because `list.index()` raises a `ValueError` if the item is not found, not returning -1; using it for membership testing is both incorrect and inefficient.

192
MCQhard

What is the output of print(type(3 + 4.5))?

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

Correct: the result is float.

Why this answer

In Python, when you add an integer (3) and a float (4.5), implicit type conversion (coercion) occurs: the integer is promoted to a float to avoid data loss. The result is 7.5, which is a float. Therefore, type(7.5) returns <class 'float'>.

Exam trap

Python Institute often tests the misconception that integer + float yields an integer, or that the type() function returns the string 'int' or 'float' rather than the actual class object.

How to eliminate wrong answers

Option A is wrong because the result of adding an int and a float is not an int; Python does not truncate or round the result to an integer. Option B is wrong because the result is not a complex number; complex numbers require an imaginary part (e.g., 3+4j). Option D is wrong because the result is a numeric value, not a string; the print function outputs the type object as a string representation, but the underlying type is float.

193
MCQeasy

Which of the following variable names is valid in Python?

A.1st_value
B._private
C.class
D.my-var
AnswerB

Underscores are allowed and often used for private attributes.

Why this answer

(_private) is valid because Python allows variable names to start with an underscore. Identifiers can consist of letters, digits, and underscores, but must not begin with a digit. The underscore is treated as a letter, so _private conforms to Python's naming rules.

Exam trap

The PCEP exam often tests the rule that identifiers cannot start with a digit, leading candidates to mistakenly think that any non-alphabetic starting character is invalid, but underscores are explicitly allowed.

How to eliminate wrong answers

Option A is wrong because variable names cannot start with a digit; '1st_value' begins with '1', which violates Python's identifier syntax. Option C is wrong because 'class' is a reserved keyword in Python and cannot be used as a variable name. Option D is wrong because the hyphen '-' is not a valid character in Python identifiers; only underscores are allowed for separation, not dashes.

194
MCQeasy

A user enters '42' at an input prompt. After executing x = input(), what is the type of x?

A.float
B.str
C.bool
D.int
AnswerB

Correct: input() returns a string

Why this answer

The `input()` function in Python always returns the user's input as a string, regardless of whether the input looks like a number. When the user enters '42', it is captured as the string '42', so the type of `x` is `str`. This is because `input()` does not perform any implicit type conversion.

Exam trap

The trap here is that candidates assume `input()` automatically converts numeric-looking input to an integer or float, because many other languages (like C++ with `cin`) do so, but Python's `input()` always returns a string.

How to eliminate wrong answers

Option A is wrong because `float` would only be the type if the code explicitly converted the input using `float(x)`, but `input()` alone returns a string. Option C is wrong because `bool` is never the default return type of `input()`; a boolean would require explicit conversion or a specific condition. Option D is wrong because `int` would require explicit conversion via `int(x)`; `input()` does not automatically parse numeric strings into integers.

195
Multi-Selecteasy

Which THREE of the following are valid ways to create a list in Python?

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

Converts tuple to list.

Why this answer

The `list()` constructor can take an iterable, such as a tuple, and convert it into a new list. `list((1, 2, 3))` explicitly creates a list `[1, 2, 3]` from the tuple `(1, 2, 3)`. This is a standard and valid way to create a list in Python.

Exam trap

The PCEP exam often tests the distinction between list literals (`[]`), tuple literals (`()`), and set literals (`{}`), trapping candidates who confuse the syntax for creating a list with that of other sequence or collection types.

196
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

197
MCQmedium

You are working on a Python application that interacts with an external API to fetch user data. The API returns JSON responses. Occasionally, the API returns a response with a missing key that your code assumes always exists, causing a KeyError. The application is critical and must continue functioning even if some data is incomplete. The data is processed in a loop over a list of user IDs. Your team lead suggests using the dictionary's get() method with a default value. However, the nested structure may have missing keys at multiple levels. What is the most robust way to handle this?

A.Use .get() with defaults for every key access, including nested ones, to avoid exceptions.
B.Check for key existence using 'in' for every key before accessing.
C.Wrap the entire loop in a try-except that catches any exception and continues.
D.Use a try-except inside the loop to catch KeyError and other expected exceptions for each item.
AnswerD

Precise exception handling allows logging and skipping only problematic items.

Why this answer

It combines targeted exception handling with loop continuity. By placing a try-except inside the loop, you catch KeyError (and optionally other expected exceptions) for each individual user ID, log or handle the failure, and then continue processing the next item. This avoids crashing the entire loop while still allowing normal processing for valid data, which is more robust than blindly using .get() on deeply nested structures or catching all exceptions outside the loop.

Exam trap

The Python Institute often tests the distinction between catching exceptions at the loop level versus inside the loop, and candidates mistakenly choose wrapping the entire loop in a try-except (Option C) because they think it handles all errors, not realizing it terminates the loop on the first failure.

How to eliminate wrong answers

Option A is wrong because .get() only handles missing keys at the level it is called; if a nested key is missing, accessing it on the result of .get() will still raise a KeyError unless every intermediate access also uses .get() with a default, which becomes cumbersome and error-prone for deeply nested JSON. Option B is wrong because checking key existence with 'in' for every key before access leads to verbose, repetitive code and still requires handling missing keys at multiple levels, often resulting in deeply nested if statements that are hard to maintain. Option C is wrong because wrapping the entire loop in a try-except catches any exception from any iteration, causing the loop to abort entirely on the first error, which defeats the requirement that the application must continue functioning even with incomplete data.

198
MCQeasy

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

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

Tuples do not support item assignment.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

199
MCQhard

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

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

Accessing a missing key raises KeyError.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

200
MCQhard

According to PEP 8, which of the following is the recommended way to name a constant representing the maximum number of retries?

A.MAX_RETRIES
B.max_retries
C.1st_retry_limit
D.maxRetries
AnswerA

Uppercase with underscores for constants.

Why this answer

PEP 8 (Python Enhancement Proposal 8) recommends that constants be named using uppercase letters with underscores separating words, i.e., `MAX_RETRIES`. This convention distinguishes constants from regular variables, which use lowercase with underscores, and helps improve code readability and maintainability.

Exam trap

The PCEP exam often tests the distinction between variable naming conventions (snake_case for variables vs. UPPER_CASE for constants) and the rule that identifiers cannot start with a digit, leading candidates to confuse camelCase or invalid names with PEP 8 recommendations.

How to eliminate wrong answers

Option B is wrong because `max_retries` follows the PEP 8 naming convention for regular variables (snake_case), not constants, which should be in all uppercase. Option C is wrong because `1st_retry_limit` starts with a digit, which is invalid in Python (identifiers cannot begin with a number) and violates PEP 8 naming rules. Option D is wrong because `maxRetries` uses camelCase, which is not recommended by PEP 8 for Python code; PEP 8 specifies snake_case for variable names and UPPER_CASE for constants.

201
MCQmedium

What is the output of the code?

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

Division yields float.

Why this answer

The expression `3 / 2` performs true division in Python, which always returns a float even if both operands are integers. The result is `1.5`, and `type(1.5)` returns `<class 'float'>`. Therefore, option B is correct.

Exam trap

Python Institute often tests the distinction between true division (`/`) and floor division (`//`), and the trap here is that candidates mistakenly think dividing two integers always yields an integer, forgetting that Python 3's `/` always returns a float.

How to eliminate wrong answers

Option A is wrong because `3 / 2` does not produce a string; it produces a numeric value, and `type()` returns a class object, not a string literal. Option C is wrong because true division (`/`) never returns an int in Python 3; 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 of `3 / 2` is not a Boolean; it is a numeric float, and `type()` would never return `<class 'bool'>` for a division operation.

202
MCQeasy

A developer writes a script to calculate the average of three numbers: avg = (a + b + c) / 3. If a=5, b=10, c=15, what is the data type of avg?

A.float
B.bool
C.int
D.str
AnswerA

Division returns a float.

Why this answer

In Python, the division operator (/) always returns a float, even when dividing integers that result in a whole number. Here, (5 + 10 + 15) / 3 equals 30 / 3, which yields 10.0, a float. Therefore, the data type of avg is float.

Exam trap

Python Institute often tests the distinction between / (true division, returns float) and // (floor division, returns int) to trap candidates who assume integer division returns an integer.

How to eliminate wrong answers

Option B is wrong because bool is a data type for Boolean values (True/False), and the result of arithmetic division cannot be a bool. Option C is wrong because int would only be the type if integer division (//) were used, but the standard division operator (/) always produces a float in Python 3. Option D is wrong because str is a string data type, and the result of numeric division is never a string unless explicitly converted.

203
MCQmedium

A program needs to check if a number is both positive and even. Which expression correctly implements this?

A.if num > 0 or num % 2 == 0:
B.if num > 0 and num % 2 == 0:
C.if num > 0 & num % 2 == 0:
D.if num > 0 and % 2 == 0:
AnswerB

Correct: both conditions must be true.

Why this answer

It uses the logical `and` operator to combine two conditions: `num > 0` (checks if the number is positive) and `num % 2 == 0` (checks if the number is even). Both conditions must be true for the overall expression to be true, which correctly implements the requirement of checking if a number is both positive and even.

Exam trap

Python Institute often tests the distinction between logical operators (`and`, `or`) and bitwise operators (`&`, `|`), as well as the correct syntax for the modulo operator, to catch candidates who confuse these concepts.

How to eliminate wrong answers

Option A is wrong because it uses the `or` operator, which returns true if either condition is true, meaning it would accept a positive odd number or a negative even number, not requiring both conditions. Option C is wrong because `&` is the bitwise AND operator, not a logical operator; it performs bitwise comparison on integers, which can produce unexpected boolean results and is not the correct way to combine conditions in an `if` statement. Option D is wrong because it has a syntax error: the modulo operator `%` is missing its left operand (it should be `num % 2 == 0`), making the expression invalid.

204
MCQeasy

What is the result of bool(0) in Python?

A.0
B.None
C.True
D.False
AnswerD

Correct; 0 is falsy.

Why this answer

The bool() function in Python converts any value to a Boolean. The integer 0 is considered a falsy value, so bool(0) returns False. This is because Python defines 0, None, empty collections, and False itself as falsy.

Exam trap

Python Institute often tests the misconception that bool(0) returns 0 or None, exploiting candidates who confuse the integer value 0 with the Boolean False, or who think that only the literal False keyword is falsy.

How to eliminate wrong answers

Option A is wrong because bool(0) does not return the integer 0; it returns a Boolean value, not an integer. Option B is wrong because bool(0) does not return None; None is a separate falsy value but is not the result of converting 0 to Boolean. Option C is wrong because 0 is not truthy; only non-zero integers evaluate to True when passed to bool().

205
MCQeasy

A Python script calculates the area of a circle: radius = 5; area = 3.14 * radius ** 2; print(area). What is printed?

A.78.5
B.157.0
C.25.0
D.31.4
AnswerA

Correct calculation.

Why this answer

78.5 because the expression `3.14 * radius ** 2` is evaluated according to Python's operator precedence: exponentiation (`**`) has higher precedence than multiplication (`*`), so `radius ** 2` computes 5 squared (25), then multiplied by 3.14 gives 78.5. The `print(area)` function outputs this value.

Exam trap

The Python Institute often tests operator precedence by embedding exponentiation in a multiplication expression, trapping candidates who mistakenly compute `(3.14 * radius) ** 2` (yielding 246.49) or who confuse area with circumference (2 * pi * r).

How to eliminate wrong answers

Option B (157.0) is wrong because it incorrectly assumes the formula uses diameter instead of radius (e.g., 3.14 * 10 ** 2 / 2 or 3.14 * 5 * 10). Option C (25.0) is wrong because it only computes `radius ** 2` and ignores multiplication by pi (3.14). Option D (31.4) is wrong because it incorrectly multiplies 3.14 by radius (5) instead of radius squared (25), effectively computing circumference (2 * pi * r) or a linear relationship.

206
MCQeasy

A QA engineer needs to run a test 5 times. Which loop construct is most appropriate?

A.do: ... while counter < 5
B.while counter < 5: ... counter += 1
C.for i in range(5): ...
D.def repeat(): ... repeat()
AnswerC

Most straightforward.

Why this answer

The `for i in range(5)` loop is the most idiomatic and concise way to repeat an action a fixed number of times (5 iterations) in Python. The `range(5)` generates a sequence from 0 to 4, and the loop body executes exactly 5 times, which directly matches the requirement to run a test 5 times without needing manual counter management.

Exam trap

The trap here is that candidates may confuse the `while` loop (option B) as equally valid, but the PCEP exam expects knowledge that `for` loops with `range` are the preferred and most Pythonic construct for fixed-count iteration, while `while` loops are intended for condition-based repetition where the number of iterations is not known in advance.

How to eliminate wrong answers

Option A is wrong because `do: ... while counter < 5` is not valid Python syntax; Python does not have a `do-while` loop construct (it uses `while` with a condition checked before each iteration). Option B is wrong because although it uses a valid `while` loop, it requires explicit initialization of `counter` before the loop and manual increment (`counter += 1`) inside the loop, making it less concise and more error-prone than the `for` loop for a fixed number of iterations. Option D is wrong because `def repeat(): ... repeat()` defines a recursive function that calls itself, which would cause infinite recursion (and a `RecursionError`) unless a base case is added; it is not a loop construct and is inappropriate for repeating a test exactly 5 times.

207
MCQhard

A server logs are stored as a list of tuples: `logs = [('2024-01-10', 'INFO', 'Started'), ('2024-01-10', 'ERROR', 'Disk full')]`. A developer wants to count how many ERROR logs exist. Which code snippet correctly counts them?

A.count = logs.count(('ERROR',))
B.count = sum(log[1] == 'ERROR' for log in logs)
C.count = [log for log in logs if log[1] == 'ERROR']
D.count = len(logs)
AnswerB

Sum of booleans gives the count.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

208
MCQhard

Which expression evaluates to False?

A.3 > 4
B.3 <= 3
C.3 == 3
D.3 != 2
AnswerA

3 is not greater than 4, so False.

Why this answer

The expression `3 > 4` evaluates to `False` in Python, as 3 is not greater than 4. All other options evaluate to `True` due to the correct application of comparison operators: `<=`, `==`, and `!=`.

Exam trap

Python Institute often tests whether candidates confuse the assignment operator `=` with the equality operator `==`, or mistakenly think that `<=` requires strict inequality, leading them to incorrectly evaluate `3 <= 3` as `False`.

How to eliminate wrong answers

Option B is wrong because `3 <= 3` evaluates to `True` — the `<=` operator returns `True` when the left operand is less than or equal to the right operand, and here they are equal. Option C is wrong because `3 == 3` evaluates to `True` — the `==` operator checks for value equality, and both integers are identical. Option D is wrong because `3 != 2` evaluates to `True` — the `!=` operator returns `True` when the operands are not equal, and 3 is indeed not equal to 2.

209
Multi-Selecthard

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

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

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

Why this answer

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

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

Exam trap

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

210
MCQhard

You are a developer on a team that maintains a legacy Python 2 codebase being migrated to Python 3. One function reads a file in text mode and counts word frequencies. In Python 2, the code used the dict.iteritems() method to iterate over the dictionary. After migration, the code raises AttributeError: 'dict' object has no attribute 'iteritems'. You need to update the code to work in Python 3 while minimizing changes. Which action should you take?

A.Replace iteritems() with viewitems().
B.Replace iteritems() with iteritems() from the six compatibility library.
C.Replace iteritems() with items().
D.Convert the dictionary to a list of tuples and iterate over the list.
AnswerC

items() in Python 3 returns a view that works similarly.

Why this answer

In Python 3, the `dict.iteritems()` method was removed because `dict.items()` now returns a view object that provides lazy iteration, similar to what `iteritems()` did in Python 2. Replacing `iteritems()` with `items()` is the minimal change that preserves the iteration behavior and works correctly in Python 3.

Exam trap

The PCEP exam often tests the misconception that Python 3 requires an external library or a different method name to achieve the same iteration behavior, when in fact `items()` alone is the correct and minimal replacement for `iteritems()`.

How to eliminate wrong answers

Option A is wrong because `viewitems()` does not exist in Python 3; it was a Python 2 method on dictionary views that is not available in Python 3. Option B is wrong because `iteritems()` from the `six` compatibility library would require adding an external dependency and is not a minimal change; the standard library already provides `items()` for the same purpose. Option D is wrong because converting the dictionary to a list of tuples is unnecessary and inefficient, as `items()` already provides the needed iteration without creating an intermediate list.

211
MCQmedium

A company needs to calculate the average of three test scores entered by a user. The scores are integers. The programmer writes the following code: s1 = input("Enter score 1: ") s2 = input("Enter score 2: ") s3 = input("Enter score 3: ") avg = (s1 + s2 + s3) / 3 print("Average:", avg) When run, the output is incorrect. What is the most likely cause?

A.The division by 3 will cause a ZeroDivisionError because 3 is not a float.
B.The division operator / always returns an integer, but the sum is not an integer.
C.The variable names s1, s2, s3 are not allowed because they start with a letter.
D.The input() function returns strings, so concatenation occurs instead of addition.
AnswerD

input() returns a string, so using + on strings concatenates them.

Why this answer

The `input()` function in Python always returns a string, even when the user types numbers. The `+` operator on strings performs concatenation (e.g., '5' + '3' + '2' becomes '532'), not numeric addition. Dividing the concatenated string by 3 then causes a `TypeError` (or produces an incorrect result if the string is implicitly converted), so the average calculation fails.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type, leading candidates to overlook the need for explicit type conversion before arithmetic operations.

How to eliminate wrong answers

Option A is wrong because dividing by an integer literal like 3 is perfectly valid; Python allows division by integers, and a `ZeroDivisionError` only occurs when dividing by zero, not by a non-zero integer. Option B is wrong because the `/` operator in Python 3 always returns a float, not an integer, and the issue is not about the return type of division. Option C is wrong because variable names starting with a letter (like s1, s2, s3) are perfectly allowed in Python; identifiers must start with a letter or underscore, so these names are valid.

212
MCQmedium

A programmer writes: result = 'Py' * 2 + 'thon'. What is the value of result?

A.'Py2thon'
B.'Python'
C.'Pyththon'
D.'PyPy'
AnswerB

Correct: 'Py'*2 = 'PyPy', plus 'thon' = 'Python'

Why this answer

In Python, the * operator on a string repeats it, and the + operator concatenates strings. 'Py' * 2 produces 'PyPy', then 'PyPy' + 'thon' results in 'Python'. This follows Python's operator precedence where * has higher precedence than +, so the multiplication is evaluated first.

Exam trap

The PCEP exam often tests the misconception that the * operator concatenates the string with the numeric value as a string (e.g., 'Py' * 2 becomes 'Py2'), or that it only repeats the last character, leading candidates to choose option A or C.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes that the * operator concatenates with a numeric representation, producing 'Py2thon', but Python's string repetition does not insert the number as a string. Option C is wrong because it suggests the repetition applies only to the last character, yielding 'Pyththon', but * repeats the entire string 'Py', not just the 'y'. Option D is wrong because it shows only the result of 'Py' * 2 as 'PyPy', ignoring the concatenation with 'thon'.

213
MCQmedium

Which of the following variable names is NOT valid in Python?

A.My_Var
B._myVar
C.2nd_place
D.myVar2
AnswerC

Invalid; starts with a digit.

Why this answer

Python variable names cannot begin with a digit. The name '2nd_place' starts with '2', which violates Python's identifier naming rules. Valid variable names must start with a letter (a-z, A-Z) or an underscore (_), followed by letters, digits, or underscores.

Exam trap

Python Institute often tests the rule that variable names cannot start with a digit, and the trap here is that candidates may focus on the underscore or mixed case and overlook the leading digit, mistakenly thinking '2nd_place' is acceptable because it contains letters and underscores.

How to eliminate wrong answers

Option A is wrong because 'My_Var' starts with a letter and contains only letters and underscores, which is perfectly valid in Python. Option B is wrong because '_myVar' starts with an underscore, which is allowed and commonly used for internal or private variables. Option D is wrong because 'myVar2' starts with a letter and contains letters and digits, which is valid as digits are allowed after the first character.

214
MCQmedium

A developer needs to check if a number is positive and even. Which conditional expression is correct?

A.if num > 0 & num % 2 == 0:
B.if num > 0 and num % 2 = 0:
C.if num > 0 && num % 2 == 0:
D.if num > 0 and num % 2 == 0:
AnswerD

Correct syntax.

Why this answer

Python uses the keyword `and` for logical conjunction, and the equality operator is `==` (not `=`). The expression `num > 0 and num % 2 == 0` correctly checks that `num` is both greater than zero and divisible by 2 with no remainder, which defines a positive even number.

Exam trap

The PCEP exam often tests the distinction between logical operators (`and`, `or`) and bitwise operators (`&`, `|`), as well as the difference between assignment (`=`) and comparison (`==`), to catch candidates who confuse syntax from other programming languages.

How to eliminate wrong answers

Option A is wrong because `&` is the bitwise AND operator in Python, not the logical AND; it would perform a bitwise operation on the boolean results, which is not the intended logic. Option B is wrong because `=` is the assignment operator, not the equality comparison operator; using `num % 2 = 0` would cause a SyntaxError. Option C is wrong because `&&` is not a valid operator in Python; it is used in languages like C, Java, and JavaScript, but Python requires the keyword `and`.

215
Matchingmedium

Match each Python list method to its effect.

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

Concepts
Matches

Adds an item to the end of the list

Inserts an item at a given position

Removes the first occurrence of a value

Removes and returns an item at a given index

Sorts the list in ascending order in place

Why these pairings

The correct matches are: insert inserts at an index, remove deletes first occurrence of a value, pop removes and returns an element by index. Common confusions involve swapping append (adds a single element) and extend (adds elements from an iterable).

216
MCQmedium

A script uses a dictionary to store counts of words. The code `counts['apple'] += 1` raises a KeyError the first time because the key doesn't exist. Which approach best solves this?

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

setdefault initializes if missing, then increment.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

217
MCQmedium

A developer runs the command and sees the output. Which statement about the data type is correct?

A.3.14 is a decimal.Decimal type.
B.3.14 is a float, but Python also treats it as a double.
C.3.14 is a float in Python.
D.3.14 is a string.
AnswerC

Correct; the type is float.

Why this answer

In Python, numeric literals with a decimal point, such as 3.14, are always interpreted as the built-in float type. Python does not have a separate 'double' type; its float is implemented as a C double (64-bit IEEE 754), but the language itself refers to it as float. This is a fundamental rule of Python's data type system.

Exam trap

The PCEP exam often tests the misconception that Python has separate 'float' and 'double' types, similar to languages like C or Java, when in fact Python's float is always double-precision and there is no distinct double type.

How to eliminate wrong answers

Option A is wrong because decimal.Decimal is a separate type from the decimal module, not a built-in literal type; 3.14 is not automatically a Decimal. Option B is wrong because Python does not have a distinct 'double' type — it uses a single float type, which is implemented as a double-precision floating-point number under the hood, but the language name is simply 'float'. Option D is wrong because 3.14 is not enclosed in quotes, so it is a numeric literal, not a string.

218
Multi-Selecteasy

Which TWO of the following are Python membership operators?

Select 2 answers
A.not
B.not in
C.in
D.is
E.and
AnswersB, C

Membership operator.

Why this answer

'not in' is a Python membership operator that returns True if a value is not found in a sequence (like a list, tuple, or string). Option C is correct because 'in' is the complementary membership operator that returns True if a value is found in a sequence. Both are used to test membership in iterable objects.

Exam trap

Python Institute often tests the distinction between membership operators ('in', 'not in') and identity operators ('is', 'is not'), as candidates frequently confuse 'is' with 'in' or mistake 'not' as a standalone membership operator when it must be paired with 'in'.

219
MCQeasy

Which of the following is a valid variable name in Python?

A.my-var
B.2nd_place
C._count
D.class
AnswerC

Underscore is allowed at start.

Why this answer

(_count) is correct because in Python, variable names can start with an underscore, and underscores are allowed anywhere in the name. The name _count follows all Python identifier rules: it starts with a letter or underscore, contains only letters, digits, or underscores, and is not a reserved keyword.

Exam trap

Python Institute often tests the rule that hyphens are not allowed in variable names, leading candidates to mistakenly think my-var is valid because it resembles common naming in other languages or file systems.

How to eliminate wrong answers

Option A is wrong because my-var contains a hyphen (-), which is not allowed in Python identifiers; only underscores are permitted as separators. Option B is wrong because 2nd_place starts with a digit, which violates Python's rule that identifiers must begin with a letter or underscore. Option D is wrong because class is a reserved keyword in Python and cannot be used as a variable name.

220
MCQmedium

A junior developer is tasked with writing a Python script that reads a list of integers from a file, removes any duplicate numbers, and then writes the unique numbers back to the same file in ascending order. The file 'numbers.txt' currently contains one integer per line. The developer writes the following code: with open('numbers.txt', 'r') as f: numbers = [int(line.strip()) for line in f] unique = list(set(numbers)) unique.sort() with open('numbers.txt', 'w') as f: for num in unique: f.write(str(num) + '\n') The script runs without errors, but the output file contains the numbers in descending order instead of ascending. The developer checks the sort() method and confirms it sorts in ascending order. What is the MOST likely cause of the issue?

A.The numbers were read as strings and the sort() method sorted them lexicographically, putting '10' before '2'.
B.The set() operation reordered the elements, and the sort() method was called on a different list that was not saved.
C.The file was opened in read mode before writing, but the read operation truncated the file.
D.The file was opened in append mode instead of write mode, causing the sorted numbers to be appended after the original unsorted numbers.
AnswerB

If the developer wrote unique = list(set(numbers)).sort(), unique would be None. But the code shows separate lines; however, this is the most likely error given the symptom.

Why this answer

The code snippet as shown uses unique.sort() to sort the list in-place and then writes the sorted list, so it would produce ascending order if executed exactly. The discrepancy between the expected ascending order and the reported descending order strongly suggests a deviation from the snippet, such as the developer accidentally calling sort() on a different list (for example, sorting the original numbers list or a temporary copy) and then writing the unsorted unique list. Option B captures this idea: the sort() method was called on a list that was not saved, leading to the unsorted list being written.

The other options are not consistent with the provided code: A is incorrect because the numbers are correctly converted to integers; C and D misrepresent file behavior (the file is opened in write mode, not append, and reading does not truncate the file).

Exam trap

The trap is that set() does not guarantee order, and sort() modifies the list in-place. Candidates may assume set() preserves order or that sort() returns a new list, leading them to miss the actual error if the code deviates from the snippet shown.

How to eliminate wrong answers

Option A is wrong because the code explicitly converts each line to an integer with int(line.strip()), so numbers are integers, not strings, and sort() will sort numerically, not lexicographically. Option C is wrong because opening a file in read mode does not truncate it; truncation only occurs when opening in write mode ('w') or with the 'x' flag. Option D is wrong because the code opens the file with 'w' mode, not append mode ('a'), so the sorted numbers overwrite the original content, not append to it.

221
MCQhard

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

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

Correct: The dictionary size changed during iteration.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

222
MCQhard

A dictionary: d = {1: 'a', 2: 'b', 3: 'c'}. Which code will cause a KeyError?

A.d.get(4)
B.if 4 in d: d[4]
C.d[4]
D.d.setdefault(4, 'd')
AnswerC

Key 4 not present.

Why this answer

Accessing a dictionary key that does not exist using square bracket notation (d[4]) raises a KeyError. Since the dictionary d has keys 1, 2, and 3, the key 4 is absent, so d[4] triggers the error.

Exam trap

The PCEP exam often tests the distinction between safe dictionary access methods (get, setdefault, in) and the direct indexing operator ([]), expecting candidates to know that only [] raises a KeyError for missing keys.

How to eliminate wrong answers

Option A is wrong because d.get(4) returns None (or a default value if provided) instead of raising an error, as the get() method is designed to safely handle missing keys. Option B is wrong because the 'if 4 in d:' condition checks for the key's existence before accessing d[4], so the block is never executed when the key is absent, preventing a KeyError. Option D is wrong because d.setdefault(4, 'd') inserts the key 4 with value 'd' into the dictionary and returns 'd', avoiding any error.

223
MCQeasy

Refer to the exhibit. What is printed?

A.None (error)
B.A
C.B
D.C
AnswerB

First condition met.

Why this answer

The code uses a `for` loop to iterate over the list `['A', 'B', 'C']`. The `break` statement inside the loop executes when the variable `letter` equals `'A'`, immediately terminating the loop. Therefore, only `'A'` is printed before the loop ends, making option B correct.

Exam trap

Python Institute often tests the misconception that `break` only exits the current iteration or that the loop continues after the break, leading candidates to think multiple values are printed.

How to eliminate wrong answers

Option A is wrong because the code does not produce an error; the `break` statement is syntactically valid and the loop runs without exception. Option C is wrong because `'B'` is never printed; the loop breaks before reaching the second iteration where `letter` would be `'B'`. Option D is wrong because `'C'` is never printed; the loop terminates at the first iteration before `'C'` is ever assigned to `letter`.

224
MCQeasy

What is the correct way to read a floating-point number from user input and store it in a variable?

A.x = input(float())
B.x = input() as float
C.x = float(input())
D.x = input().float()
AnswerC

Reads input as string, then converts to float.

Why this answer

`float(input())` first reads the user input as a string via `input()`, then converts that string to a floating-point number using the `float()` function. This is the standard and only valid way in Python to obtain a float from console input, as `input()` always returns a string.

Exam trap

The trap here is that candidates often confuse the order of operations, thinking they can apply a type conversion method directly on the input string (like `.float()`) or use non-existent syntax like `as float`, instead of wrapping the `input()` call with the `float()` function.

How to eliminate wrong answers

Option A is wrong because `input(float())` attempts to call `float()` with no argument (which returns 0.0) and then passes that float as the prompt argument to `input()`, not converting the user's input. Option B is wrong because `x = input() as float` is not valid Python syntax; the `as` keyword is used only in `with` statements and exception handling, not for type conversion. Option D is wrong because `x = input().float()` tries to call a method named `float()` on the string returned by `input()`, but strings have no such method, causing an AttributeError.

Page 2

Page 3 of 7

Page 4

All pages