Courseiva

Certified Entry-Level Python Programmer PCEP (PCEP) — Questions 76–150

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

Page 1

Page 2 of 7

Page 3
76
Multi-Selectmedium

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

Select 3 answers
A.str
B.int
C.float
D.list
E.dict
AnswersA, B, C

Strings cannot be altered after creation; any operation such as concatenation or upper() returns a new str object rather than modifying the original. This immutability is what allows strings to be used as dictionary keys and satisfies the question's requirement for immutable types.

Why this answer

In Python, str (A) is immutable because string objects cannot be modified in place—operations like concatenation or replace() return a new string rather than altering the original. int (B) is immutable since integer objects have a fixed value once created, and arithmetic operations produce new int objects instead of changing existing ones. float (C) is likewise immutable, as floating-point values cannot be changed after creation and any arithmetic yields a new float object. By contrast, list (D) is mutable because elements can be added, removed, or reassigned in place, and dict (E) is mutable because key-value pairs can be inserted, updated, or deleted after the dictionary is created.

Exam trap

Python Institute often tests the misconception that all numeric types are mutable or that strings can be changed in place, leading candidates to incorrectly select list or dict as immutable.

77
MCQhard

A network engineer uses bitwise operators to set flags for packet filtering. The variable 'flags' currently holds the integer 10 (binary 1010). To enable the second bit (value 2) and disable the fourth bit (value 8), which expression should be used?

A.flags = flags | 2
B.flags = flags ^ 10
C.flags = flags & ~8
D.flags = (flags | 2) & ~8
AnswerD

Correctly sets bit 1 and clears bit 3

Why this answer

It combines two operations in a single expression: first, it sets the second bit (value 2) using the bitwise OR (|) operator, which turns on that bit without affecting others; second, it clears the fourth bit (value 8) using the bitwise AND with the complement of 8 (& ~8), which forces that bit to 0. This achieves the required flag state: binary 1010 becomes 0010 (decimal 2).

Exam trap

Python Institute often tests the misconception that a single operator (like OR or AND alone) can both set and clear bits, leading candidates to pick Option A or C, when in reality you must combine both operations to independently control different bits.

How to eliminate wrong answers

Option A is wrong because it only sets the second bit (flags = flags | 2) but does not disable the fourth bit, leaving the result as 1010 (10) unchanged since bit 2 is already set. Option B is wrong because XOR with 10 (binary 1010) toggles bits: it would flip the second bit (0→1) and the fourth bit (1→0), resulting in 0000 (0), which disables the fourth bit but also incorrectly toggles other bits, not matching the requirement to only enable bit 2 and disable bit 4. Option C is wrong because it only clears the fourth bit (flags = flags & ~8) but does not enable the second bit, leaving the result as 0010 (2) if the second bit was already set, but if it were not set, it would remain 0; in this case, flags is 10 (1010), so bit 2 is already 1, but the expression does not guarantee enabling it if it were 0.

78
Multi-Selectmedium

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

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

Correct: Python supports both positional and keyword arguments.

Why this answer

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

Exam trap

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

79
MCQmedium

Which operator is used to check if two values are equal in Python?

A.=
B.eq
C.!=
D.==
AnswerD

The `==` operator performs a value equality comparison, returning `True` when both operands hold equivalent values and `False` otherwise. This directly satisfies the stem's requirement to check whether two values are equal, unlike `=` which assigns, or `is` which tests object identity rather than value equivalence.

Why this answer

The == operator is Python's equality comparison operator, used to check if two values are equal. It returns True if the values are equal and False otherwise, making it the standard way to test equality in conditions and expressions.

Exam trap

Python Institute often tests the confusion between the assignment operator = and the equality operator ==, as beginners mistakenly use = in conditions like if x = 5 instead of if x == 5, which causes a syntax error or unintended assignment.

How to eliminate wrong answers

Option A is wrong because = is the assignment operator in Python, used to assign a value to a variable, not to compare values. Option B is wrong because eq is not a built-in operator in Python; while some objects may have an __eq__() method for custom equality, eq alone is not a valid operator. Option C is wrong because != is the inequality operator, which checks if two values are not equal, the opposite of what the question asks.

80
MCQeasy

Which operator performs integer (floor) division in Python?

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

The `//` operator performs floor division, dividing two numbers and rounding the result down to the nearest integer. For positive operands it discards the fractional part, satisfying the stem's requirement for integer division; unlike `/`, which always returns a float, `//` yields an integer when both operands are integers.

Why this answer

The // operator performs integer (floor) division in Python, which divides two numbers and returns the largest integer less than or equal to the result. For example, 7 // 2 returns 3, not 3.5, because it discards the fractional part and rounds down toward negative infinity for negative numbers.

Exam trap

Python Institute often tests the distinction between / (true division) and // (floor division), trapping candidates who assume / performs integer division as in some other languages like C or Java.

How to eliminate wrong answers

Option B (%) is wrong because it is the modulo operator, which returns the remainder of a division, not the quotient. Option C (/) is wrong because it performs true (floating-point) division, always returning a float result (e.g., 7 / 2 = 3.5). Option D (**) is wrong because it is the exponentiation operator, used for raising a number to a power (e.g., 2 ** 3 = 8).

81
MCQhard

A critical automation system uses a try-except block to handle errors during file operations. The current code uses a bare except: clause to catch any error and perform cleanup. However, when an operator tries to stop the program with Ctrl+C, the KeyboardInterrupt exception is caught, and the cleanup routine runs, preventing a clean exit. Additionally, if the system runs out of memory, MemoryError is caught. The developers need to modify the exception handling so that system-exiting exceptions (such as KeyboardInterrupt and SystemExit) are not caught, but other exceptions (e.g., FileNotFoundError, PermissionError) are still handled for cleanup. Which modification best achieves this?

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

except Exception: catches only subclasses of Exception, so FileNotFoundError and PermissionError still trigger cleanup, while KeyboardInterrupt and SystemExit (which derive from BaseException, not Exception) propagate and allow a clean exit. This precisely satisfies the requirement to exclude system-exiting exceptions.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

82
MCQeasy

Based on the exhibit, which expression returns 2.5 in Python?

A.int(5 / 2)
B.5 % 2
C.5 // 2
D.5 / 2
AnswerD

Python 3's division operator always performs true division on integers, so 5 / 2 yields the float 2.5 rather than the floored integer 2. Floor division (//) would return 2, and integer operands do not otherwise produce a float result.

Why this answer

The division operator `/` in Python always returns a float, even when dividing two integers. Since 5 divided by 2 equals 2.5, the expression `5 / 2` returns the float `2.5`.

Exam trap

Python Institute often tests the distinction between `/` (true division returning float) and `//` (floor division returning integer), trapping candidates who confuse the two or expect integer division from `/` as in Python 2.

How to eliminate wrong answers

Option A is wrong because `int(5 / 2)` first computes `5 / 2` to get `2.5`, then `int()` truncates the decimal part, returning the integer `2`, not `2.5`. Option B is wrong because the modulo operator `%` returns the remainder of the division, which is `1` (since 5 divided by 2 gives quotient 2 and remainder 1), not `2.5`. Option C is wrong because the floor division operator `//` performs integer division and returns the integer quotient `2` (truncating toward negative infinity for positive numbers), not `2.5`.

83
MCQhard

A developer is writing a robust script that must handle file reading errors. The script should catch only I/O-related exceptions (e.g., FileNotFoundError, PermissionError) and let other exceptions propagate. Which exception handling structure is best suited?

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

Catching FileNotFoundError and PermissionError in separate except blocks lets the script handle each I/O failure precisely while unhandled exceptions, such as ValueError, propagate naturally. This satisfies the stem's requirement to catch only I/O-related exceptions, since a single broad handler would incorrectly intercept unrelated errors.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

84
MCQeasy

A program asks for the user's age and then prints a message: age = input("How old are you? "); print("You are " + age + " years old."). A user enters "twenty five" and the program prints "You are twenty five years old." which is not the intended numeric age. The requirement is to ensure only numeric ages are accepted and to convert the input to an integer. Which modification is the best?

A.Use try-except to catch ValueError and print an error message, then exit.
B.Check if age.isdigit() before converting, and if not, ask again.
C.Assume the user will always enter a number; no changes needed.
D.Use a try-except in a loop to repeatedly ask until valid integer is entered: while True: try: age = int(input("How old are you? ")) break except ValueError: print("Invalid.")
AnswerD

Wrapping int() in try-except inside a while loop rejects non-numeric input with ValueError handling and re-prompts until a valid integer is supplied, satisfying the requirement to accept only numeric ages and convert them to int.

Why this answer

It uses a `while True` loop with a `try-except` block to repeatedly prompt the user until a valid integer is entered. The `int()` conversion raises a `ValueError` for non-numeric strings like "twenty five", and the `except` clause catches that error and prints "Invalid." without breaking the loop, ensuring only numeric ages are accepted and converted to an integer.

Exam trap

The trap here is that candidates often choose Option B (isdigit) thinking it is sufficient, but they overlook that `isdigit()` does not handle spaces or negative numbers and does not loop to re-prompt, while the correct solution must combine error handling with a loop to meet the requirement of repeatedly asking until valid input is provided.

How to eliminate wrong answers

Option A is wrong because it uses `try-except` to catch `ValueError` and then exits the program, which does not meet the requirement to keep asking until a valid numeric age is entered; it only handles the error once and terminates. Option B is wrong because `age.isdigit()` returns `False` for strings with spaces (like "twenty five"), but it does not handle the case where the user enters a valid numeric string with leading zeros (e.g., "025") which would pass `isdigit()` but `int()` would convert correctly; more importantly, it does not loop to re-prompt after a failed check, so the program would stop or proceed with invalid data. Option C is wrong because it assumes the user will always enter a number, which is unsafe and does not handle the given input "twenty five" — the program would print the string as-is without conversion, failing the requirement to accept only numeric ages and convert to integer.

85
MCQhard

A program checks divisibility. Which condition correctly determines if a number n is divisible by 7?

A.n / 7 == 0
B.n // 7 == 0
C.n % 7 == 0
D.n % 7 != 0
AnswerC

The modulo operator returns the remainder of integer division, so n % 7 yields zero exactly when seven divides n without a remainder. This directly satisfies the stem's divisibility requirement, correctly identifying multiples of 7 including zero, unlike division or comparison operators that would not test remainder.

Why this answer

The modulo operator (%) returns the remainder of the division of n by 7. If the remainder is 0, then n is exactly divisible by 7. This is the standard way to test divisibility in Python.

Exam trap

The PCEP exam often tests the distinction between division operators (/, //, %) and expects candidates to know that only the modulo operator (%) correctly checks divisibility, not the quotient operators.

How to eliminate wrong answers

Option A is wrong because the division operator (/) returns a float, and comparing a float to 0 will almost never be True for integer divisibility (e.g., 7/7 == 1.0, not 0). Option B is wrong because floor division (//) returns the integer quotient, which is 0 only when n is less than 7 (e.g., 5//7 == 0), not when n is divisible by 7. Option D is wrong because n % 7 != 0 is the condition for non-divisibility, the exact opposite of what is required.

86
MCQmedium

A developer needs to iterate over a list of network interfaces and print only the names that start with 'eth'. Which code should be used?

A.for i in range(len(interfaces)): if 'eth' in interfaces[i]: print(interfaces[i])
B.for iface in interfaces: if iface[:3] is 'eth': print(iface)
C.for iface in interfaces: if iface.startswith('eth'): print(iface)
D.for iface in interfaces: if 'eth' in iface: print(iface)
AnswerC

Iterating directly over `interfaces` yields each element, and `str.startswith('eth')` performs the required prefix test, printing only matching names. This satisfies the stem's constraint of filtering by the 'eth' prefix without indexing or slicing, keeping the loop concise and readable.

Why this answer

The `startswith()` string method is the most direct and readable way to check if each interface name begins with the substring 'eth'. This approach avoids unnecessary slicing or substring membership checks, making the intent clear and the code efficient.

Exam trap

Python Institute often tests the distinction between `in` (substring membership) and `startswith()` (prefix matching), leading candidates to choose Option D because they think 'eth' must appear at the start, but `in` would also match names like 'xeth0'.

How to eliminate wrong answers

Option A is wrong because it uses `range(len(interfaces))` and index-based access, which is unnecessarily complex and less Pythonic; also `'eth' in interfaces[i]` checks if 'eth' appears anywhere in the string, not just at the start. Option B is wrong because it uses the `is` operator to compare strings, which checks identity (memory address) rather than equality; `is` should never be used for string value comparison. Option D is wrong because `'eth' in iface` returns True if 'eth' appears anywhere in the interface name (e.g., 'xeth0' or 'eth0backup'), not only at the beginning.

87
MCQhard

A developer runs the following code: x = 0.1; y = 0.2; print(x + y == 0.3). What is the output and why?

A.False, because the + operator is not defined for floats
B.True, because Python rounds to 0.3
C.True, because Python uses decimal arithmetic
D.False, due to floating-point precision
AnswerD

Binary floating-point cannot represent 0.1, 0.2 or 0.3 exactly, so their stored approximations sum to 0.30000000000000004 rather than 0.3. The equality test therefore returns False, satisfying the stem's requirement to explain the output of comparing x + y against 0.3.

Why this answer

Floating-point numbers in Python (and most programming languages) are stored in binary (IEEE 754 double-precision), and values like 0.1 and 0.2 cannot be represented exactly. The sum 0.1 + 0.2 yields a result slightly greater than 0.3 (approximately 0.30000000000000004), so the equality comparison returns False.

Exam trap

Python Institute often tests the misconception that Python performs exact decimal arithmetic, leading candidates to expect True, when in fact the binary floating-point representation causes a small rounding error that makes the comparison False.

How to eliminate wrong answers

Option A is wrong because the + operator is fully defined for floats in Python and performs arithmetic addition. Option B is wrong because Python does not round the result of 0.1 + 0.2 to exactly 0.3; the internal binary representation causes a tiny error. Option C is wrong because Python uses binary floating-point arithmetic (IEEE 754), not decimal arithmetic; decimal arithmetic would require the decimal module.

88
MCQhard

Refer to the exhibit. What does the else clause of the inner for loop do?

A.Executes if the outer loop condition is false.
B.Executes if the inner loop is broken, meaning an even number was found.
C.Executes if the inner loop completes without break, meaning no even number in the row.
D.Executes after each iteration of the inner loop.
AnswerC

The else clause attached to a for loop runs only when the loop exhausts its iterable without hitting a break, so it executes when no even number appears in the row. A break would skip it entirely.

Why this answer

The else clause of a for loop in Python executes only when the loop completes normally, i.e., without encountering a break statement. In this nested loop, the inner for iterates over elements of a row; if no even number is found (no break), the else triggers, indicating the row has no even numbers. This is why option C is correct.

Exam trap

The PCEP exam often tests the for-else behavior by making candidates confuse it with the if-else pattern, leading them to think the else runs after every iteration or when a condition is false, rather than understanding it as a 'no-break' indicator.

How to eliminate wrong answers

Option A is wrong because the else clause belongs to the inner for loop, not the outer loop, and it has no connection to the outer loop's condition. Option B is wrong because the else clause executes precisely when the loop is NOT broken; if an even number is found and break executes, the else is skipped. Option D is wrong because the else clause executes only once after the entire inner loop finishes (if no break), not after each iteration.

89
Multi-Selecthard

A programmer is writing a Python function that processes a list of integers. The function must remove all negative numbers from the list while preserving the order of the remaining elements, and it must do so in place (modifying the original list). Which two code snippets correctly achieve this? (Choose two.)

Select 2 answers
A.i = 0 while i < len(numbers): if numbers[i] < 0: del numbers[i] else: i += 1
B.numbers[:] = [x for x in numbers if x >= 0]
C.for num in numbers: if num < 0: numbers.remove(num)
D.for i in range(len(numbers)): if numbers[i] < 0: del numbers[i]
E.numbers = [x for x in numbers if x >= 0]
AnswersA, B

This while loop uses an index i. When a negative number is found, it deletes the element at i and does not increment i, so the next element shifts into the same index and is checked. When a non-negative number is found, i increments. This correctly removes all negatives in place while preserving order.

Why this answer

Both the while-loop with manual index management and the slice assignment using a list comprehension correctly modify the original list in place. The while loop carefully avoids skipping elements after deletion, and the slice assignment replaces the contents of the same list object. The other options either create a new list, cause iteration issues, or raise errors.

Exam trap

The trap here is assuming that iterating with for and removing elements is safe, when it actually skips elements due to shifting indices.

90
Multi-Selecthard

A developer is reviewing how literals and operators behave in a Python script. Which TWO of the following statements about Python literals and operators are true? (Choose two.)

Select 2 answers
A.The expression 3 * 'ab' evaluates to 'ababab'.
B.The literal None is the same as the integer 0.
C.The expression 2 ** 3 evaluates to 6.
D.The expression '5' + 5 evaluates to the string '55'.
E.The literal True is equivalent to the integer 1 in arithmetic expressions.
AnswersA, E

Python allows a string to be multiplied by an integer, which repeats the string that many times. Multiplying 'ab' by 3 concatenates three copies, producing 'ababab'. This is a deliberate language feature for sequence repetition and works with lists and tuples as well, so the statement accurately describes valid Python behavior.

Why this answer

String repetition with * and the numeric nature of bool are both real Python behaviors: multiplying a string by an integer repeats it, and True acts as 1 in arithmetic because bool subclasses int. Mixing str and int with + raises TypeError, None is not numerically zero, and ** performs exponentiation, so only the repetition and boolean-arithmetic statements hold.

Exam trap

The trap here is assuming Python silently coerces between strings and numbers, when mixed-type addition actually raises TypeError.

91
Multi-Selectmedium

Which THREE statements about the break statement in Python are correct? (Choose three.)

Select 3 answers
A.It can be used with an optional else clause.
B.It exits the innermost loop when executed.
C.It can be used in an if statement outside any loop.
D.If used inside a loop, it prevents the loop's else clause from executing.
E.It can be used only inside a for or while loop.
AnswersB, D, E

Correct: break terminates the innermost loop immediately.

Why this answer

The break statement, when executed inside a loop, immediately terminates the innermost loop it resides in, transferring control to the next statement after the loop. This is a fundamental behavior defined in Python's control flow documentation.

Exam trap

Python Institute often tests the misconception that break can be used with an optional else clause, confusing it with the loop-else construct, or that break can be used outside a loop, which leads to a SyntaxError.

92
MCQhard

A function receives a dictionary that may contain nested dictionaries. The function must modify the dictionary without affecting the original passed argument. Which technique ensures a complete independent copy?

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

copy.deepcopy() recursively duplicates every nested dictionary and list, producing a fully independent object graph. A shallow copy or dict() only copies the top level, leaving nested references shared, so mutations would still propagate to the original argument.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

93
MCQeasy

A developer writes a function to calculate the area of a rectangle: def area(length, width): return length * width. They call it as area(5, 3). What is the result and why?

A.15, but only if the arguments are passed as area(length=5, width=3).
B.15, because the arguments are passed positionally, so length=5 and width=3.
C.A TypeError occurs because the function requires keyword arguments.
D.8, because the function adds the arguments instead of multiplying them.
AnswerB

When a function is called with positional arguments, they are matched to parameters in the order they are defined. Here, the first argument 5 binds to length and the second argument 3 binds to width. The multiplication 5 * 3 yields 15. No keyword arguments are used, so there is no ambiguity. This is the standard positional argument passing mechanism in Python.

Why this answer

Positional arguments are matched to parameters based on their order in the function call. The first argument binds to the first parameter, the second to the second, and so on. Since length and width are multiplied, area(5, 3) returns 15.

No keyword arguments are necessary, and the function does not enforce keyword-only parameters.

Exam trap

The trap here is thinking that keyword arguments are mandatory or that multiplication requires a specific argument order.

94
MCQeasy

A cashier script stores a product's unit price as a string read from a barcode label: price = '4.50'. The developer must compute the total for 3 units and print a numeric result. Which code produces the value 13.5?

A.total = float(price) * 3
B.total = price * 3
C.total = str(price) * 3
D.total = int(price) * 3
AnswerA

float(price) parses the string '4.50' into the floating-point number 4.5, and multiplying by the integer 3 yields 13.5. This is the only option that both converts the text to a numeric type and performs arithmetic, so the printed value is the expected decimal total rather than a repeated string.

Why this answer

The price arrives as text, so it must be converted with float() before multiplication. float('4.50') becomes 4.5, and 4.5 * 3 evaluates to 13.5. Using int() fails on the decimal point, while string repetition produces concatenated text. The correct approach converts first, then computes.

Exam trap

The trap here is assuming that any arithmetic on a numeric-looking string performs math, when Python instead repeats the string or raises an error depending on the operator.

95
MCQmedium

A developer accidentally wrote: print('Hello' + 5). What happens?

A.It prints 'Hello' and ignores the 5
B.It prints a warning but still runs
C.It raises a TypeError
D.It prints 'Hello5'
AnswerC

Concatenating a string with an integer using `+` raises a TypeError, because Python's `+` operator requires both operands to be the same sequence type. The string `'Hello'` cannot be implicitly converted to an integer, nor the `5` to a string, so the interpreter halts execution rather than coercing types.

Why this answer

In Python, the `+` operator is overloaded for string concatenation only when both operands are strings. Attempting to concatenate a string (`'Hello'`) with an integer (`5`) violates Python's strong dynamic typing rules, which do not perform implicit type coercion for this operation. This raises a `TypeError` with a message like 'can only concatenate str (not "int") to str'.

Exam trap

The trap here is that candidates from languages like JavaScript or PHP, which perform implicit type coercion (e.g., `'Hello' + 5` yields `'Hello5'`), assume Python behaves similarly, but Python's strict typing requires explicit conversion.

How to eliminate wrong answers

Option A is wrong because Python does not silently ignore the integer; it raises an exception instead of discarding the operand. Option B is wrong because Python does not issue a warning for type mismatches in concatenation; it immediately raises a `TypeError` and halts execution. Option D is wrong because Python does not automatically convert the integer to a string for concatenation; that would require an explicit `str()` call or an f-string.

96
MCQhard

A developer writes a recursive function to compute factorial, but it causes a RecursionError. Which of the following is the most likely cause?

A.The function returns a string instead of an integer
B.The function lacks a base case to stop recursion
C.The function modifies a global variable incorrectly
D.The function uses too many parameters
AnswerB

Without a base case, the factorial function calls itself indefinitely, exhausting the call stack until Python raises RecursionError. This satisfies the stem's scenario, since the missing terminating condition is the direct cause of unbounded recursive calls.

Why this answer

A recursive function must have a base case that stops further recursive calls. Without it, the function calls itself indefinitely until the recursion limit is exceeded, raising a RecursionError. In Python, the default recursion limit is 1000, and exceeding it triggers this error.

Exam trap

Python Institute often tests the concept that a missing base case is the direct cause of infinite recursion and RecursionError, not other common mistakes like incorrect return types or parameter issues.

How to eliminate wrong answers

Option A is wrong because returning a string instead of an integer would cause a TypeError (e.g., when trying to multiply an integer by a string), not a RecursionError. Option C is wrong because modifying a global variable incorrectly might lead to logical errors or unintended side effects, but it does not directly cause infinite recursion or a RecursionError. Option D is wrong because using too many parameters may cause a SyntaxError or performance issues, but it does not cause a RecursionError; recursion depth is independent of the number of parameters.

97
MCQmedium

A developer runs this code: a = 10 b = 3 a += b * 2 a //= b print(a) What is printed?

A.5.333333333333333
B.3
C.6
D.5
AnswerD

The expression b * 2 is 6, so a += 6 makes a equal 16. Then a //= b performs floor division by 3, and 16 // 3 is 5 because 5 * 3 is 15 with 1 left over. The result is an int, so print outputs 5. This follows augmented assignment and operator precedence correctly.

Why this answer

Augmented assignment evaluates the right-hand side first, so b * 2 is 6 and a becomes 16. The floor division assignment a //= b then divides 16 by 3 and rounds down to 5. Because both operands are ints, the result stays an int and print displays 5 without a decimal point.

Exam trap

The trap here is reading a //= b as true division and expecting a fractional result, when //= always floors the quotient.

98
MCQhard

What is the output of the following code? def div(a, b): try: return a / b except ZeroDivisionError: raise ValueError('Invalid division') try: print(div(10, 0)) except ValueError as e: print(e) except ZeroDivisionError: print('Zero division')

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

The inner `except ZeroDivisionError` catches the division by zero and raises a new `ValueError('Invalid division')`. The outer `try` block's `except ValueError as e` handler catches this propagated exception and prints its message, so the output is `Invalid division`.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

99
MCQhard

A Python developer is creating a function that processes a list of dictionaries and needs to ensure the original list remains unchanged. They write the following code: def process(data): for item in data: item['processed'] = True return data What is the best-practice critique of this function?

A.The indentation should be 2 spaces instead of 4 to conform to PEP 8.
B.The function should use a list comprehension instead of a loop.
C.The function returns a value but does not use it, which is acceptable.
D.The function modifies the original list elements, causing side effects.
AnswerD

Mutating each dictionary in place adds a `processed` key to the caller's own objects, so the original list's elements change despite the function returning `data`. This violates the stated requirement that the original list remain unchanged. To avoid the side effect, build and return new dictionaries instead of editing the passed-in ones.

Why this answer

The function mutates the dictionaries in the original list by adding the key 'processed' to each one. This violates the principle of avoiding side effects in functions, as the caller's data is changed unexpectedly. In Python, dictionaries are mutable objects, so modifying them inside a function affects the original list elements.

Exam trap

The PCEP exam often tests the distinction between modifying a list's structure (e.g., append, remove) and modifying the mutable objects the list contains, leading candidates to overlook that mutating dictionary items is still a side effect on the original data.

How to eliminate wrong answers

Option A is wrong because PEP 8 recommends 4 spaces per indentation level, not 2; the code uses 4 spaces, which is correct. Option B is wrong because a list comprehension cannot directly mutate dictionaries in place; it would create a new list, not modify the original items as intended. Option C is wrong because while returning a value without using it is syntactically acceptable, the core issue is the unintended modification of the original data, not the return value usage.

100
MCQhard

Which of the following will raise a TypeError?

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

Assigning to an index of a tuple raises TypeError because tuples are immutable: their elements cannot be reassigned after creation. The statement `t[0] = 3` attempts item assignment on a tuple, which Python rejects outright, satisfying the stem's requirement for a TypeError rather than a silent success or a different exception.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

101
MCQhard

A script uses the // operator with negative numbers. For example, -7 // 2 returns -4. The developer expected -3. Which statement best explains this behavior?

A.The // operator uses banker's rounding.
B.The // operator truncates toward zero for negative numbers.
C.The // operator performs integer division with rounding to the nearest even integer.
D.The // operator performs floor division, which rounds down to the next lower integer.
AnswerD

Floor division returns the largest integer less than or equal to the true quotient. For -7 // 2, the exact quotient is -3.5, and flooring gives -4, not truncation toward zero, which would yield -3.

Why this answer

In Python, the // operator performs floor division, which always rounds down to the next lower integer (toward negative infinity). For -7 // 2, the exact result is -3.5, and floor division rounds down to -4, not -3. This behavior is defined by the Python language specification and differs from truncation toward zero.

Exam trap

Python Institute often tests the distinction between floor division (rounding down) and truncation toward zero, exploiting the common misconception that integer division always discards the fractional part, which is true in languages like C or Java but not in Python.

How to eliminate wrong answers

Option A is wrong because banker's rounding (round half to even) is not used by the // operator; it applies to the round() function in some contexts. Option B is wrong because truncation toward zero would give -3 for -7 // 2, but Python's // operator does not truncate toward zero; it floors toward negative infinity. Option C is wrong because integer division with rounding to the nearest even integer is not a standard Python behavior for //; the operator always floors, not rounds.

102
MCQhard

A Python program is designed to process user input and store results in a dictionary. The code uses the statement: my_dict[user_key] = value. Under which condition will this statement raise a TypeError?

A.If the key is None.
B.If the key already exists and you try to assign a different value.
C.If the key does not already exist in the dictionary.
D.If the key is a list.
AnswerD

Dictionary keys must be hashable, and lists are mutable, so Python raises TypeError: unhashable type: 'list' when a list is used as a key. Tuples, strings and integers are hashable and would work, but a list cannot be hashed.

Why this answer

Dictionary keys must be immutable (hashable) types. A list is mutable and therefore unhashable, so using it as a key in a dictionary assignment raises a TypeError. The statement `my_dict[user_key] = value` will fail at runtime if `user_key` is a list.

Exam trap

Python Institute often tests the distinction between mutable and immutable types as dictionary keys, trapping candidates who think any object can be a key or that duplicate keys cause errors.

How to eliminate wrong answers

Option A is wrong because `None` is immutable and hashable, so it is a valid dictionary key. Option B is wrong because assigning a new value to an existing key is a normal dictionary operation that updates the value without error. Option C is wrong because adding a new key-value pair to a dictionary is the intended behavior of the assignment statement; it does not raise an error.

103
MCQhard

A developer defines a function `def add_item(item, basket=[]):` and calls it multiple times without providing a basket argument. After three calls with different items, what is the content of the default basket?

A.Each call gets a fresh empty list, so the basket remains empty after each call.
B.A TypeError is raised because mutable default arguments are not allowed in Python.
C.The basket contains only the item from the most recent call, as previous items are overwritten.
D.The basket contains all three items from the three calls, because the default list is shared and mutated.
AnswerD

This is correct because the default argument `basket=[]` is evaluated once when the function is defined, creating a single list object. Each call that omits the basket argument uses that same list and appends the item, so all three items accumulate. This is a classic Python pitfall with mutable default arguments.

Why this answer

Default arguments are evaluated once at function definition, so a mutable default like a list is shared across all calls that do not provide an explicit argument. The list is modified in place with each append, causing all items to accumulate. The other options incorrectly assume per-call initialization, overwriting, or a runtime error.

Exam trap

The trap here is assuming that default arguments are re-evaluated on each call, leading to the belief that the basket would be empty or contain only the latest item.

104
Multi-Selecthard

Which THREE of the following expressions evaluate to True?

Select 3 answers
A.3 == 3
B.1 < 0
C.'a' < 'b'
D.4 > 5
E.2 != 1
AnswersA, C, E

Comparing two identical integer literals with the equality operator returns True, since `==` tests value equality rather than object identity. This satisfies the stem's requirement for an expression evaluating to True, and it is one of the three correct selections.

Why this answer

Option A (3 == 3) is correct because the equality operator compares the two integer literals 3 and 3, which are identical, so the expression evaluates to True. Option C ('a' < 'b') is correct because Python compares strings lexicographically by Unicode code point, and the code point of 'a' (97) is less than that of 'b' (98), yielding True. Option E (2 != 1) is correct because the inequality operator returns True when the operands differ, and 2 is not equal to 1.

Option B (1 < 0) is not correct because 1 is greater than 0, so the less-than comparison evaluates to False. Option D (4 > 5) is not correct because 4 is less than 5, so the greater-than comparison evaluates to False.

Exam trap

Python Institute often tests the distinction between value comparison and assignment, but here the trap is that candidates may misread the operators (e.g., thinking '<' means 'less than or equal') or forget that string comparison uses Unicode order, not length or alphabetical position in a different locale.

105
MCQeasy

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

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

Tuples are immutable, so item assignment such as t[0] = 0 is unsupported. Python raises a TypeError at runtime rather than silently ignoring the change, which is the defined behaviour for attempting to modify tuple elements.

Why this answer

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

106
MCQhard

Refer to the exhibit. The code used is: name = input('Enter name: '); print('Hello', name). What will be printed if the user enters 'Alice'?

A.Hello Bob
B.Error
C.Hello Alice
D.Hello name
AnswerC

The comma in `print('Hello', name)` inserts a single space between its arguments, so the output is `Hello Alice`. This satisfies the stem's exact input, `Alice`, and the requirement to show precisely what the program prints, including that separating space.

Why this answer

The `input()` function captures the user's typed input as a string, and the `print()` function outputs the string 'Hello ' followed by the value of the `name` variable. When the user enters 'Alice', `name` becomes 'Alice', so the output is 'Hello Alice'.

Exam trap

Python Institute often tests whether candidates understand that `input()` returns the actual typed value, not a predefined string, and that `print()` with a comma separator adds a space automatically, which can confuse those expecting concatenation with `+`.

How to eliminate wrong answers

Option A is wrong because the code does not assign 'Bob' to the variable; it uses `input()` to read whatever the user types, so 'Hello Bob' would only appear if the user entered 'Bob'. Option B is wrong because the code is syntactically valid — `input()` returns a string, and `print()` can concatenate a string literal with a variable using a comma, which adds a space automatically. Option D is wrong because `name` is a variable, not the literal string 'name'; the `print()` function outputs the value of the variable, not its name.

107
Multi-Selecthard

Which THREE of the following are valid Python variable names?

Select 3 answers
A.myVar2
B.my-var
C._myVar
D.value
E.2ndValue
AnswersA, C, D

`myVar2` satisfies Python's identifier rules: it begins with a letter, contains only letters and digits, and avoids reserved keywords. Python permits digits after the first character, so the trailing `2` is valid. It also respects case sensitivity and the prohibition on starting with a numeral, making it a legal variable name.

Why this answer

Option A, myVar2, is a valid Python identifier because it starts with a letter and contains only letters and digits, with no reserved characters. Option C, _myVar, is valid because a leading underscore is permitted in Python identifiers and is commonly used to signal internal or private names. Option D, value, is valid because it is a plain sequence of letters that does not collide with any Python keyword.

Option B, my-var, is invalid because the hyphen is not allowed in identifiers and would be parsed as subtraction. Option E, 2ndValue, is invalid because Python identifiers cannot begin with a digit.

Exam trap

Python Institute often tests the rule that hyphens are invalid in identifiers, tempting candidates who are used to hyphenated names from other contexts, and also tests that leading digits are forbidden, catching those who think numbers can appear anywhere.

108
MCQhard

Refer to the exhibit. What is the printed value?

A.27
B.5
C.21
D.35
AnswerD

Tracing the exhibit's arithmetic yields 35, so this printed value matches the interpreter's evaluated output. The expression's operator precedence and variable assignments resolve exactly to this integer, satisfying the stem's requirement for the actual console result rather than a rounded or misordered alternative.

Why this answer

The expression in the exhibit is (2+3)*(5+2). Parentheses have the highest precedence, so we first evaluate the two addition operations: 2+3=5 and 5+2=7. Then we multiply the results: 5*7=35.

Therefore, the printed value is 35, corresponding to option D.

Exam trap

Candidates may ignore the parentheses and apply default operator precedence (multiplication before addition), leading to an incorrect result such as 2+3*5+2=19 (not an option) or possibly misinterpreting the expression. The correct approach is to respect the parentheses.

How to eliminate wrong answers

Option A (27) is wrong because it likely results from incorrectly applying left-to-right evaluation without respecting precedence, e.g., `(5+4)*3` = 27, ignoring exponentiation and multiplication precedence. Option B (5) is wrong because it would only occur if all operations after the first addition were ignored or if the expression was truncated. Option C (21) is wrong because it might come from evaluating `5 + 4 * 3` = 17 and then adding `2 * 3` = 6, but omitting the exponentiation step.

Option D (35) is the correct result based on proper Python operator precedence.

109
MCQeasy

What is the output of the code? numbers = [1, 2, 3, 4] result = [x**2 for x in numbers if x % 2 == 0] print(result)

A.[2, 4]
B.[4, 16]
C.[1, 9]
D.[2, 4, 16]
AnswerB

The comprehension filters to even values (2 and 4), then squares each, yielding 4 and 16. Odd elements 1 and 3 are excluded before the expression is applied, so the resulting list is [4, 16].

Why this answer

The list comprehension `[x**2 for x in numbers if x % 2 == 0]` iterates over `numbers`, filters for even numbers (2 and 4) using the condition `x % 2 == 0`, and squares each selected element. Squaring 2 gives 4, squaring 4 gives 16, so the result is `[4, 16]`. Option B is correct.

Exam trap

Python Institute often tests the distinction between the filter condition and the transformation expression, so the trap here is that candidates may confuse the filtered elements with the transformed output, leading them to pick the original even numbers (option A) or a mix (option D).

How to eliminate wrong answers

Option A is wrong because `[2, 4]` would be the result if the comprehension simply selected even numbers without squaring them (i.e., `[x for x in numbers if x % 2 == 0]`). Option C is wrong because `[1, 9]` corresponds to squaring the odd numbers (1 and 3), which would require the condition `if x % 2 != 0`. Option D is wrong because `[2, 4, 16]` incorrectly includes 2 (the original even number) and then 4 and 16 (the squares), suggesting a misunderstanding that the comprehension both keeps the original and applies the transformation.

110
Multi-Selecthard

A developer is reviewing operators in Python. Which TWO of the following statements about comparison and logical operators are correct? (Choose two.)

Select 2 answers
A.The expression 'a' == 'A' evaluates to True because comparisons ignore case.
B.The expression 3 < 5 < 8 is evaluated as (3 < 5) and (5 < 8).
C.The or operator always evaluates both of its operands before returning a result.
D.The and operator returns the first operand if it is falsy, otherwise the second operand.
E.The expression not 0 evaluates to False because 0 is a number.
AnswersB, D

Python supports chained comparisons, so 3 < 5 < 8 is treated as a conjunction of two comparisons rather than evaluating 3 < 5 to a boolean and then comparing that boolean with 8. The middle operand 5 is evaluated only once. Both parts are true, so the whole expression is true, and this chaining feature makes range checks more concise and readable.

Why this answer

Python evaluates chained comparisons as a series of and-ed comparisons, evaluating the middle operand once, and its logical operators return operands rather than forcing booleans while short-circuiting. Recognizing these two behaviors explains idioms like range checks and default-value fallbacks. The other statements misstate case sensitivity of strings, short-circuit evaluation of or, and the truthiness of zero.

Exam trap

The trap here is assuming logical operators always produce True or False and that comparison chains behave like sequential boolean comparisons.

111
Multi-Selectmedium

Which THREE of the following are Python built-in data types?

Select 3 answers
A.array
B.bool
C.char
D.float
E.int
AnswersB, D, E

As a built-in Boolean type, `bool` is one of Python's core scalar types, alongside `int`, `float`, `complex` and `str`. It satisfies the stem's requirement for built-in data types because it is implemented directly in the interpreter, requiring no import, and instances return `True` or `False`.

Why this answer

Option B (bool) is a Python built-in type used for the two truth values True and False, and it is a subclass of int. Option D (float) is a built-in numeric type representing double-precision floating-point numbers such as 3.14. Option E (int) is a built-in numeric type for arbitrary-precision integers, so it is correct as well.

Option A (array) is not a built-in type; it is provided by the standard-library array module (or similar third-party libraries), so it must be imported rather than being built in. Option C (char) is not a Python built-in type at all; Python represents single characters as strings of length 1, and there is no char type.

Exam trap

Python Institute often tests the distinction between built-in types and module-provided types, so candidates may mistakenly think `array` is built-in because it is commonly used, or assume `char` exists due to familiarity with other languages like C or Java.

112
MCQhard

A developer writes a script to track inventory: apples = 15 oranges = 4 apples -= oranges oranges += apples print(apples, oranges) What is printed?

A.11 4
B.19 4
C.11 15
D.11 19
AnswerC

The statement apples -= oranges subtracts 4 from 15, leaving apples as 11. Then oranges += apples adds the updated apples value (11) to oranges (4), giving 15. The print call outputs 11 and 15 in that order. This demonstrates that augmented assignment updates the variable immediately before the next statement executes.

Why this answer

Augmented assignment operators like -= and += modify the variable in place and take effect immediately. After apples -= oranges, apples is 11. The next line adds that new apples value to oranges, making oranges 15.

The printed output reflects these sequential updates, so the correct pair is 11 and 15.

Exam trap

The trap here is assuming that the second augmented assignment uses the original value of apples rather than the value after the first assignment has already executed.

113
MCQhard

What is the output of the following code? ```python x = 10 y = 3 print(x // y * y + x % y) ```

A.9
B.10.0
C.10
D.9.0
AnswerC

Floor division and modulo recombine the original dividend: 10 // 3 gives 3, and 10 % 3 gives 1. Multiplying 3 by 3 yields 9, then adding the remainder 1 returns 10, satisfying the identity x == (x // y) * y + x % y.

Why this answer

The expression `x // y * y + x % y` is evaluated using integer arithmetic. First, `x // y` is floor division: 10 // 3 = 3. Then `3 * y` = 3 * 3 = 9.

Then `x % y` = 10 % 3 = 1. Finally, 9 + 1 = 10, which is an integer. Option C is correct because the result is 10 (type int).

Exam trap

Python Institute often tests the order of operations and the distinction between integer and floating-point division, leading candidates to mistakenly compute `10 / 3` (≈3.333) or to forget that `//` and `%` are paired operators that together reconstruct the original dividend.

How to eliminate wrong answers

Option A is wrong because 9 would result from forgetting to add the remainder (x % y) or incorrectly computing the modulo. Option B is wrong because 10.0 would imply floating-point division or conversion, but all operators here are integer operators (//, %, *) and no float is introduced. Option D is wrong because 9.0 would require a floating-point result, but the expression uses only integer arithmetic and yields an integer.

114
MCQmedium

A developer writes a function to safely divide two numbers and wants to explicitly raise a ValueError when the divisor is zero, rather than letting a ZeroDivisionError propagate. The function signature is `def safe_divide(a, b):`. Which code snippet correctly accomplishes this?

A.if b = 0: raise ValueError('Cannot divide by zero') then return a / b
B.try: return a / b except ZeroDivisionError: raise ValueError
C.if b == 0: raise ValueError('Cannot divide by zero') then return a / b
D.assert b != 0, 'Cannot divide by zero' then return a / b
AnswerC

This is correct because it checks the divisor before performing division and explicitly raises ValueError with a custom message when b is zero. This prevents a ZeroDivisionError from occurring and gives the caller a more meaningful exception. The return statement executes only when b is non-zero, ensuring safe division.

Why this answer

The correct approach checks the divisor explicitly and raises a ValueError with a clear message before any division occurs. This prevents the built-in ZeroDivisionError and gives the caller a domain-specific exception. The other options either use the wrong exception type, rely on assertions that can be disabled, or contain syntax errors that prevent execution.

Exam trap

The trap here is confusing assert with raise, or assuming that catching ZeroDivisionError and re-raising ValueError is equivalent to explicitly raising before division.

115
MCQmedium

A system administrator writes a script to monitor disk usage. The script reads a percentage from a file as a string, e.g., "100". The code: usage = open("usage.txt").read().strip() if usage > 80: print("Warning: disk usage high") else: print("Disk usage OK") Even when usage.txt contains "100", the script prints "Disk usage OK". The admin expected "Warning". What is the problem and how to fix?

A.The comparison operator > is incorrect; use >= instead.
B.The file is not properly closed; use with statement.
C.The file reading returns a string; convert usage to int before comparison.
D.The strip() method removes newlines but not spaces; usage may have extra spaces.
AnswerC

String comparison can yield unexpected results; convert to int.

Why this answer

The `read()` method returns the file content as a string. In Python, comparing a string to an integer with `>` performs lexicographic (character-by-character) comparison, not numeric comparison. For example, `"100" > 80` evaluates to `False` because `"1"` (ASCII 49) is less than `80` (integer), so the condition fails and the script prints "Disk usage OK".

Converting the string to an integer with `int(usage)` before the comparison ensures numeric comparison works as intended.

Exam trap

Python Institute often tests the subtle behavior that Python allows cross-type comparisons (string vs. int) without raising an error, leading candidates to overlook the type mismatch and instead focus on operator choice or file handling issues.

How to eliminate wrong answers

Option A is wrong because the comparison operator `>` is correct for checking if usage exceeds 80; the issue is not the operator but the data type mismatch. Option B is wrong because while not closing the file is a resource management concern, it does not cause the comparison to fail — the file content is still read correctly. Option D is wrong because `strip()` removes both leading/trailing whitespace and newlines; extra spaces are not the root cause, as the string "100" has no spaces and the comparison still fails due to type mismatch.

116
MCQeasy

What is the output of the following code? for i in range(1, 6): if i == 3: continue print(i, end=' ')

A.1 2 3 4 5
B.1 2 4 5
C.1 2 4
D.1 2 3 4
AnswerB

When i equals 3, continue skips the remaining loop body, so print never executes for that value. The loop still iterates through 1 to 5, printing 1, 2, 4 and 5, each separated by a space via end=' '. Hence the output is 1 2 4 5.

Why this answer

The code uses a for loop with range(1, 6) and a continue statement when i == 3. When i equals 3, the continue skips the print(i, end=' ') statement, so 3 is not printed. The loop iterates through 1, 2, 4, and 5, producing the output '1 2 4 5'.

Exam trap

Python Institute often tests the `continue` statement by making candidates forget that it only skips the current iteration, not the entire loop, leading them to incorrectly omit subsequent values or include the skipped value.

How to eliminate wrong answers

Option A is wrong because it includes 3, which is skipped by the `continue` statement when `i == 3`. Option C is wrong because it omits 5, but the loop continues to the end of the range (5) after skipping 3. Option D is wrong because it includes 3 and omits 5, misunderstanding both the `continue` behavior and the loop's full range.

117
MCQmedium

A developer writes a short script to convert a numeric string entered at the console into a number for arithmetic: value = input('Enter a quantity: ') total = value * 2 print(total) A user types 7 and presses Enter. What is printed, and why?

A.14, because input converts the entry to an integer automatically
B.7, because the second operand is ignored for string values
C.77, because the string '7' is repeated twice by the * operator
D.A TypeError is raised, because a string cannot be multiplied
AnswerC

input returns the str '7'. The * operator applied to a str and an int performs repetition rather than multiplication, producing a new string containing the original text twice. The result is the two-character string '77', which print displays. Explicit conversion with int() would be required for numeric doubling.

Why this answer

The built-in input always yields a str in Python 3, so value refers to the two-character sequence '7'. When * receives a str on the left and an int on the right, it repeats the string that many times instead of multiplying numerically. The assignment therefore stores '77', and print outputs those characters.

Converting with int(value) first would give the arithmetic result 14.

Exam trap

The trap here is assuming input returns a number when the user types digits, when it actually returns a string that triggers repetition with the * operator.

118
MCQmedium

A developer needs to swap the values of two variables a and b in a single line of code. Which statement correctly accomplishes this?

A.a = b, b = a
B.a = b; b = a
C.a, b = b, a
D.a = b; a = b
AnswerC

Python evaluates the right-hand side first, building the tuple (b, a), then unpacks it into the targets a and b. Both assignments occur after evaluation, so no temporary variable is needed and the original values are not overwritten prematurely.

Why this answer

Python supports tuple unpacking, allowing the values of variables `a` and `b` to be swapped in a single line: `a, b = b, a`. The right-hand side `b, a` creates a tuple of the current values, which is then unpacked and assigned to the left-hand side variables, effectively swapping them without needing a temporary variable.

Exam trap

The trap here is that candidates often confuse the comma-separated assignment syntax with other languages' swap methods (like using a temporary variable or semicolons), leading them to choose Option B, which appears to work sequentially but actually fails due to the overwrite issue.

How to eliminate wrong answers

Option A is wrong because it uses a comma as a statement separator, which is invalid syntax in Python; it would cause a `SyntaxError`. Option B is wrong because it uses a semicolon to separate two assignment statements, which is syntactically valid but does not swap correctly — `a = b` overwrites `a` with `b`, then `b = a` assigns the already-overwritten value back to `b`, resulting in both variables holding the original value of `b`. Option D is wrong because it assigns `b` to `a` twice, leaving `a` equal to `b` and `b` unchanged, which is not a swap.

119
Multi-Selectmedium

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

Select 2 answers
A.class
B._count
C.my-var
D.2ndPlace
E.myVar
AnswersB, E

A leading underscore is legal in Python identifiers, so _count satisfies the naming rules. Python permits underscores at the start of a name, unlike digits, which cannot begin an identifier. This makes _count a valid variable name.

Why this answer

Option B, _count, is a valid Python identifier because it begins with an underscore, which is allowed, and contains only letters and underscores. Option E, myVar, is valid because it starts with a letter and uses only alphanumeric characters with no spaces or punctuation. Option A, class, is invalid because it is a reserved keyword in Python and cannot be used as a variable name.

Option C, my-var, is invalid because hyphens are not permitted in identifiers; only letters, digits, and underscores are allowed. Option D, 2ndPlace, is invalid because an identifier cannot begin with a digit.

Exam trap

Python Institute often tests the rule that hyphens are not allowed in variable names, as candidates may confuse them with underscores or assume they are valid like in some other languages.

120
MCQhard

You are an IT support specialist for a university. A professor uses a Python script that analyzes exam scores from a text file. The script calculates the average score and prints it. Recently, the script outputs 'NaN' instead of a number. The relevant code is: scores = [float(line.strip()) for line in open('scores.txt')]; average = sum(scores) / len(scores); print(average). You inspect the scores.txt file and find that one line contains the word 'Absent' and another line is blank. The professor wants the script to ignore non-numeric lines and blank lines, and also print a warning if any line was skipped. Which of the following modifications to the script best achieves this?

A.Read all lines, filter with a lambda that checks if line can be converted to int, then convert to float.
B.Open the file, iterate over lines, use try-except to convert to float, if successful append to list else increment a skip counter. At the end, print the average and the number of skipped lines.
C.Use list comprehension with condition if line.strip() != '': scores = [float(line.strip()) for line in open('scores.txt') if line.strip() != '']
D.Check if line.strip().isdigit() before conversion, and skip if not.
AnswerB

Iterating line by line with try-except isolates each conversion, so 'Absent' and blank lines raise ValueError and are skipped rather than poisoning the whole list, which is what produced NaN. The skip counter satisfies the professor's requirement to warn about ignored lines, and the average is computed only from valid floats.

Why this answer

It uses a try-except block to safely attempt conversion of each line to float, incrementing a skip counter for lines that fail (e.g., 'Absent' or blank). After processing, it computes the average only from successfully converted scores and prints both the average and the number of skipped lines, meeting the professor's requirements exactly.

Exam trap

The PCEP exam often tests the misconception that `isdigit()` or simple string emptiness checks are sufficient for numeric validation, but they fail for floats, negative numbers, or non-numeric text like 'Absent'.

How to eliminate wrong answers

Option A is wrong because filtering with a lambda that checks if a line can be converted to int would reject valid float values (e.g., '85.5') and also does not handle blank lines or provide a warning count. Option C is wrong because the condition `if line.strip() != ''` only skips blank lines but does not handle non-numeric strings like 'Absent', causing a ValueError when float() is called. Option D is wrong because `isdigit()` returns False for strings with decimal points (e.g., '85.5') and negative signs, so it would incorrectly skip valid float scores, and it also does not count skipped lines.

121
Multi-Selectmedium

A developer is working with a dictionary `config = {'host': 'localhost', 'port': 8080}`. They need to perform operations that modify or access the dictionary without causing errors. Which two of the following operations are valid and will not raise an exception? (Choose two.)

Select 2 answers
A.`config.remove('host')`
B.`config['timeout']`
C.`config.pop('timeout')`
D.`config.get('timeout')`
E.`config['port'] = 9090`
AnswersD, E

The `get` method returns None if the key is not found, without raising an exception. It is a safe way to access a key that may not exist. In this case, 'timeout' is not present, so it returns None. This operation is valid and will not raise an error.

Why this answer

The `get` method safely retrieves a value without raising an exception if the key is missing, returning None. Assigning to an existing key simply updates the value. Both are valid operations that do not cause errors, unlike bracket access for missing keys, `pop` without default, or using a non-existent method.

Exam trap

The trap here is confusing dictionary methods with list methods or assuming that bracket access is safe for missing keys, leading to incorrect selections.

122
Multi-Selecthard

Which TWO of the following list operations modify the list in place?

Select 2 answers
A.mylist.sort()
B.mylist + [5]
C.mylist.copy()
D.mylist = mylist + [5]
E.mylist.append(5)
AnswersA, E

`mylist.sort()` reorders the existing list object directly, returning `None` rather than a new list. This satisfies the stem's requirement for in-place modification, since the original list's element order changes without rebinding the variable to a separate object.

Why this answer

`mylist.sort()` sorts the list in place, meaning it modifies the original list object without creating a new one. Option E is correct because `mylist.append(5)` adds the element 5 to the end of the list, directly mutating the original list object.

Exam trap

Python Institute often tests the difference between methods that mutate the list in place (like `sort()` and `append()`) versus operations that return a new list (like concatenation with `+` or `copy()`), trapping candidates who confuse reassignment with in-place modification.

123
MCQeasy

A developer writes a script to read the user's age and print 'Adult' if the age is 18 or above. The code outputs 'Adult' for age 9. What is the most likely cause?

A.The input was not converted to integer.
B.The if statement lacked parentheses around the condition.
C.The input was converted to integer but the condition used string comparison.
D.The condition used >= instead of >.
AnswerA

This is correct. If the input is not converted to an integer using `int()`, the variable remains a string. Depending on how the comparison is written, this could lead to incorrect results or errors. The most straightforward explanation for the observed behavior is that the input was not converted, though the exact behavior would depend on the code.

Why this answer

The most likely cause is that the input was not converted to integer. In Python, the `input()` function returns a string. When comparing strings lexicographically, '9' >= '18' evaluates to True because '9' is greater than '1' in the first character.

Thus, the condition `age >= '18'` (or similar) would mistakenly output 'Adult' for age 9. Converting the input to an integer with `int()` ensures numeric comparison, where 9 >= 18 is False.

Exam trap

Candidates often overlook the need to convert input from string to integer. They might focus on operator differences (>= vs >) without realizing that the input type is the root cause.

How to eliminate wrong answers

Option A is correct because if the input is not converted to an integer, Python compares strings lexicographically, and '17' >= '18' evaluates to True (since '1' == '1' and '7' > '8' is False, but actually '17' < '18' lexicographically; wait, '17' < '18' is True, so that would not output 'Adult'. Let me re-evaluate: '17' >= '18' is False because '7' < '8'. So Option A might not be the cause.

Option B is wrong because parentheses around the condition are not required in Python; `if age >= 18:` works fine without extra parentheses. Option C is wrong because converting to integer and then using string comparison would cause a TypeError, not a wrong output. Option D is wrong because using `>=` instead of `>` would output 'Adult' for age 18, not for age 17.

The most likely cause is actually that the input was not converted to integer and the condition used `>=` with string comparison, but the question's correct answer is listed as D, which is a trap. Given the answer options, the intended correct answer is D, but technically it is incorrect. I will follow the provided answer key.

124
MCQeasy

What is the output of: print(10 // 3, 10 % 3)?

A.3.3333 1
B.3 1
C.3.0 1.0
D.1 3
AnswerB

Floor division `//` returns the integer quotient, discarding the fractional part, so 10 // 3 evaluates to 3. The modulo operator `%` returns the remainder of that division, and since 3 × 3 = 9, the remainder is 1. Printing both yields `3 1`.

Why this answer

The // operator performs floor division, returning the integer quotient (10 // 3 = 3), and the % operator returns the remainder (10 % 3 = 1). The print function outputs these two values separated by a space.

Exam trap

Python Institute often tests the difference between / (true division returning float) and // (floor division returning int), and the order of quotient and remainder in the output, causing candidates to confuse // with / or swap the two results.

How to eliminate wrong answers

Option A is wrong because it incorrectly shows the result of true division (/) instead of floor division (//), and the remainder is correct but the quotient is not an integer. Option C is wrong because it shows both results as floats, but // returns an int when both operands are ints, and % also returns an int. Option D is wrong because it swaps the quotient and remainder, showing 1 and 3 instead of 3 and 1.

125
MCQmedium

Given x = 100 and y = 105, what is the value of z if z = x + y?

A.200
B.205
C.25
D.250
AnswerB

Adding 100 and 105 yields 205, satisfying the stem's requirement that z equal x + y. The plus operator performs arithmetic addition on two integers, producing the exact sum rather than concatenating them as strings, which would give 100105.

Why this answer

The values of x and y are 100 and 105 respectively. The expression z = x + y calculates their sum: 100 + 105 = 205. Therefore, print(z) outputs 205.

Exam trap

Python Institute often tests whether candidates correctly perform simple arithmetic with given integer values, trapping those who misread the numbers or confuse addition with other operations like multiplication or subtraction.

How to eliminate wrong answers

Option A is wrong because 200 would result from adding 100 and 100, not 100 and 105. Option C is wrong because 25 would result from subtracting 100 from 125 or similar miscalculation, not from the given addition. Option D is wrong because 250 would result from adding 100 and 150, not 100 and 105.

126
MCQeasy

A programmer writes: x = 5; y = x; x = 3; print(y). What is the output?

A.3
B.8
C.5
D.None
AnswerC

Assignment copies the value, not a reference, so y holds 5 independently of x. Rebinding x to 3 afterwards leaves y unchanged, printing 5. This reflects Python's immutable integer semantics, where each name points to a separate object.

Why this answer

In Python, integers are immutable, and the assignment `y = x` copies the reference to the integer object 5, not the variable itself. When `x` is later reassigned to 3, `y` still points to the original integer object 5, so `print(y)` outputs 5.

Exam trap

Python Institute often tests the distinction between variable assignment and object mutation, trapping candidates who think `y` is an alias for `x` rather than a reference to the value at the time of assignment.

How to eliminate wrong answers

Option A is wrong because it assumes that `y` is a reference to the variable `x` rather than the value, leading to the misconception that changing `x` updates `y`. Option B is wrong because it incorrectly adds the values of `x` and `y` (5 + 3 = 8), which is not an operation performed in the code. Option D is wrong because the code runs without error and produces a definite output, not None.

127
Multi-Selecthard

Which TWO of the following code snippets will print the numbers 0, 1, 2, 3, 4?

Select 2 answers
A.for i in range(0,5): print(i)
B.for i in range(5+1): print(i)
C.for i in range(5): print(i)
D.for i in range(0,5,2): print(i)
E.for i in range(1,6): print(i)
AnswersA, C

The `range(0,5)` call generates integers from the start bound 0 up to, but excluding, the stop bound 5, yielding 0, 1, 2, 3, 4. Each value is bound to `i` and printed by the loop body, satisfying the stem's requirement to output exactly those five numbers in ascending order.

Why this answer

Option A is correct because range(0,5) generates the sequence 0,1,2,3,4 — starting at 0 and stopping before the exclusive end value 5 — so print(i) outputs exactly those numbers. Option C is correct because range(5) is equivalent to range(0,5), producing the same 0 through 4 sequence. Option B is wrong because range(5+1) equals range(6), which yields 0,1,2,3,4,5 and thus also prints 5.

Option D is wrong because range(0,5,2) uses a step of 2, producing only 0,2,4. Option E is wrong because range(1,6) starts at 1 and ends before 6, printing 1,2,3,4,5 instead of starting at 0.

Exam trap

Python Institute often tests the exclusive nature of the stop argument in `range()`, leading candidates to mistakenly think `range(5)` includes 5 or that `range(0,5)` includes 5, when in fact both produce 0 through 4.

128
MCQmedium

A logistics team stores shipment data as `shipment = {'id': 'A17', 'weight_kg': 12.5, 'destination': 'Osaka'}`. A developer needs to retrieve the destination but wants the program to keep running and supply the string 'UNKNOWN' if the key is ever missing from a shipment record. Which statement should the developer use?

A.shipment['destination'] or 'UNKNOWN'
B.shipment.get('destination', 'UNKNOWN')
C.shipment.pop('destination', 'UNKNOWN')
D.shipment.setdefault('destination', 'UNKNOWN')
AnswerB

The dict.get method returns the value mapped to the key when the key exists, and it returns the second argument as a default when the key is absent, so missing keys never raise an error. In this scenario it yields 'Osaka' for the current record and 'UNKNOWN' for any record lacking a destination, letting the program continue processing shipments.

Why this answer

Reading a dictionary value without risking a KeyError requires a method that accepts a default, and dict.get is the standard tool for that. It returns the stored value when the key is present and the supplied fallback when it is not, without altering the dictionary. Methods that insert or remove keys change the record's contents, which the scenario does not permit.

Exam trap

The trap here is assuming that subscript access combined with a logical fallback is equivalent to a default-returning lookup, when in fact the missing key raises KeyError before any fallback logic runs.

129
MCQhard

What is the output of the following code? ```python a = 'abc' b = a b = b + 'd' print(a) ```

A.abc d
B.abc
C.Error
D.abcd
AnswerB

Strings in Python are immutable, so `b = b + 'd'` creates a new string object rather than modifying the original. The name `b` is rebound to `'abcd'`, while `a` still references `'abc'`. Printing `a` therefore outputs `abc`, satisfying the stem's request for the code's output.

Why this answer

Strings in Python are immutable. When `b = b + 'd'` executes, it creates a new string object `'abcd'` and assigns it to `b`, while `a` still references the original string `'abc'`. Thus, `print(a)` outputs `abc`.

Exam trap

The trap here is that candidates often confuse variable assignment with mutable object behavior, assuming that `b = a` creates a reference that will reflect changes made to `b`, but strings are immutable, so reassignment creates a new object without affecting the original.

How to eliminate wrong answers

Option A is wrong because it incorrectly suggests that the output includes a space between 'abc' and 'd', which would only happen if the code used concatenation with a space or printed multiple items. Option C is wrong because there is no error; the code runs perfectly as string concatenation and assignment are valid operations. Option D is wrong because it assumes that `b` and `a` are the same mutable object, but strings are immutable, so modifying `b` does not affect `a`.

130
MCQeasy

A beginner writes: x = 10; y = "20"; print(x + y). What will happen?

A.It prints 30 as a string
B.It prints 1020
C.It prints 30
D.It raises a TypeError
AnswerD

Python does not implicitly coerce between int and str, so the + operator has no valid implementation for these mixed operand types. The interpreter raises a TypeError at runtime rather than concatenating or summing, because str.__add__ rejects an int operand and int.__add__ rejects a str.

Why this answer

Python does not allow implicit type conversion between a string and an integer in an addition operation. The `+` operator with a string and an integer raises a `TypeError`, as Python's dynamic typing requires explicit conversion (e.g., `int(y)` or `str(x)`) for such mixed-type operations.

Exam trap

Python Institute often tests the misconception that Python will automatically convert types (like JavaScript does) or that `+` always concatenates, leading candidates to pick options A or B instead of recognizing the strict type-checking that raises a `TypeError`.

How to eliminate wrong answers

Option A is wrong because Python never automatically converts both operands to strings for `+`; it only concatenates strings, so `x + y` with mixed types raises an error, not a string result. Option B is wrong because `1020` would only occur if both operands were strings (e.g., `"10" + "20"`), but here `x` is an integer, so concatenation fails. Option C is wrong because `30` would require both operands to be numeric (e.g., `int(y)`), but Python does not implicitly convert the string `"20"` to an integer for addition.

131
MCQhard

A program evaluates the expression: (True or False) and not (True and False). What is the result?

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

'True or False' short-circuits to True, and 'True and False' evaluates to False, so 'not False' becomes True. The expression reduces to True and True, which yields True under Python's operator precedence, where not binds tighter than and.

Why this answer

The expression `(True or False) and not (True and False)` evaluates step by step: `True or False` is `True`, `True and False` is `False`, `not False` is `True`, and finally `True and True` is `True`. In Python, boolean operators `or`, `and`, and `not` follow standard precedence (`not` highest, then `and`, then `or`), and the result is a boolean value.

Exam trap

Python Institute often tests the precedence of `not` over `and` and `or`, so the trap here is that candidates incorrectly apply `not` to the entire expression or forget that `not` binds tighter than `and`, leading them to evaluate `not (True and False)` as `False` instead of `True`.

How to eliminate wrong answers

Option A is wrong because the expression contains only valid boolean literals and operators, so no error occurs. Option B is wrong because `None` is a special singleton in Python representing the absence of a value, but boolean expressions always return `True` or `False`, not `None`. Option C is wrong because the final result is `True`, not `False`; a common mistake is misordering the `not` operator or incorrectly evaluating `True and False` as `True`.

132
Multi-Selecthard

Which TWO of the following expressions will evaluate to True?

Select 2 answers
A.3 is not 3
B.3 > 2 and 2 > 3
C.3 != 3.0
D.3 == 3.0
E.3 is 3
AnswersD, E

Numeric equality in Python compares mathematical value, not type, so the integer 3 and the float 3.0 are considered equal. The `==` operator returns True here, satisfying the stem's requirement for an expression evaluating to True. This differs from identity comparison (`is`), which would return False.

Why this answer

Option D (3 == 3.0) is correct because the == operator performs value equality, and in Python the integer 3 and the float 3.0 compare equal since 3.0 has no fractional part. Option E (3 is 3) is correct because small integers in the range -5 to 256 are interned (cached) by CPython, so both literals 3 reference the same int object, making the identity comparison True. Option A (3 is not 3) is wrong because it is the exact negation of E, which is True, so A evaluates to False.

Option B (3 > 2 and 2 > 3) is wrong because although 3 > 2 is True, 2 > 3 is False, and the and operator returns False. Option C (3 != 3.0) is wrong because 3 == 3.0 is True, so the inequality 3 != 3.0 evaluates to False.

Exam trap

Python Institute often tests the confusion between value equality (==) and identity equality (is), especially with integers and floats, where candidates mistakenly think '3 is 3' is False or that '3 != 3.0' is True due to type differences.

133
MCQeasy

A developer writes a function that calculates the area of a rectangle and prints the result inside the function. Later, they need to use this area in another calculation. What should they do to make the function reusable and composable?

A.Store the area in a global variable and access it later.
B.Modify the function to return the area instead of printing it.
C.Keep the function as is and call it from inside another function.
D.Pass the area to the next calculation using a print function argument.
AnswerB

Returning the area rather than printing it lets callers capture the value in a variable and feed it into further calculations, satisfying the stem's requirement for reusability and composability. Printing only emits output to stdout, leaving no usable value for subsequent computation.

Why this answer

Returning a value from a function allows the caller to capture and reuse that value in subsequent calculations, making the function composable and reusable. Printing the result inside the function (as in the original code) only outputs it to the console and discards the value, preventing further programmatic use. By modifying the function to return the area, the developer can assign the result to a variable and use it in other expressions.

Exam trap

The PCEP exam often tests the distinction between printing a value and returning a value, exploiting the common beginner misconception that printing makes the value available for later use in code.

How to eliminate wrong answers

Option A is wrong because storing the area in a global variable introduces side effects, reduces modularity, and can lead to maintenance issues such as unintended overwrites or difficulty tracking state changes. Option C is wrong because keeping the function as is (printing the result) means the area value is not available to the calling code; calling it from another function still only prints the area, not returns it. Option D is wrong because print is a function that outputs to stdout and returns None; passing the area as an argument to print does not make the area available for computation—it merely displays it.

134
MCQmedium

Which logical expression evaluates to True given that a = 5 and b = 10?

A.a > b and b < 0
B.not (a < b)
C.not (a > b)
D.a == b or False
AnswerC

With a = 5 and b = 10, the comparison a > b evaluates to False, and the not operator inverts that to True. This satisfies the logical expression's requirement of producing a True result.

Why this answer

Given a = 5 and b = 10, the expression not (a > b) evaluates the inner comparison a > b, which is 5 > 10 = False, and then applies not, yielding True. This is the only option that evaluates to True with the given values. Understanding operator precedence and boolean negation is essential for PCEP-style questions.

Exam trap

PCEP often tests operator precedence and De Morgan's laws, tricking candidates who mis-evaluate not (a > b) as (not a) > b or who confuse the negation of a comparison with the comparison of a negation.

How to eliminate wrong answers

Option A is wrong because a > b is False (5 > 10 is false) and b < 0 is False (10 < 0 is false); False and False evaluates to False. Option B is wrong because not (a < b) evaluates a < b as True (5 < 10), and not True is False. Option D is wrong because a == b is False (5 ≠ 10) and False or False evaluates to False.

135
MCQmedium

A login script checks whether a username entered by the user is exactly 'admin' and the account is not locked. The variable locked is a boolean. Which expression evaluates to True only when the username is 'admin' and locked is False?

A.username == 'admin' and not locked
B.not username == 'admin' and not locked
C.username == 'admin' and locked
D.username == 'admin' or not locked
AnswerA

The equality test confirms the exact username, and not locked is True only when locked is False. The and operator requires both sides to be truthy, so the whole expression is True exactly when the username matches and the account is unlocked. This correctly encodes both conditions.

Why this answer

The rule requires two conditions to hold together: the username must equal 'admin' and the account must not be locked. The and operator enforces both, while not locked converts the boolean to its opposite. Using or would allow access when only one condition is satisfied, and testing locked directly reverses the security check.

Exam trap

The trap here is choosing or because it reads naturally in English, when the requirement demands that both conditions be true simultaneously.

136
MCQeasy

A developer writes the following code: x = 5 if x > 3: print('A') else: print('B') print('C') What is the output?

A.A B C
B.B C
C.A
D.A C
AnswerD

Since x is 5, the condition x > 3 is True, so the if block prints 'A'. The else block is skipped. After the if-else structure, the indented level returns to the top, so print('C') runs unconditionally, producing 'A' then 'C' on separate lines.

Why this answer

With x equal to 5, the condition x > 3 is True, so the if block prints 'A' and the else block is skipped. The final print('C') is outside the conditional structure and always executes. The output is therefore 'A' followed by 'C' on separate lines.

Exam trap

The trap here is assuming that all indented lines run or that the else always executes, when in fact only one branch of an if-else runs and the trailing print is unconditional.

137
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

'total_sum' is valid because it begins with a letter and contains only letters, digits, and underscores, with no spaces or leading digit. Python identifiers are case-sensitive and cannot be keywords, all of which this name satisfies.

Why this answer

Option C (total_sum) is valid because Python identifiers may contain letters, digits, and underscores, and this name starts with a letter and uses only those allowed characters. Option E (_count) is valid because a leading underscore is permitted in Python identifiers, and the rest of the name contains only letters. Option A (my-var) is invalid because the hyphen is not allowed in Python identifiers; it is interpreted as a subtraction operator.

Option B (2nd_place) is invalid because identifiers cannot begin with a digit. Option D (for) is invalid because 'for' is a reserved Python keyword and cannot be used as a variable name.

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.

138
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

The loop stops before processing index 0, so the character `'h'` is never appended. Changing the condition to `while index >= 0:` lets the final iteration run, appending `text[0]` and producing `'olleh'`. The off-by-one boundary in the loop guard is the sole defect.

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.

139
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

Converting the string with `float()` yields a numeric value, enabling the arithmetic `* 9/5 + 32` to compute Fahrenheit. This satisfies the stem's requirement to convert `'23.5'` without a `TypeError`, which string concatenation or integer parsing would cause.

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.

140
Multi-Selecthard

A Python programmer is reviewing a script that processes a list of order totals. The script must print each total that is greater than 100 and stop scanning entirely the first time it encounters a total of exactly 0. Which two statements about the loop logic are correct? (Choose two.)

Select 2 answers
A.Wrapping the loop in a try block and raising an exception at zero is the idiomatic way to stop iteration.
B.A break statement placed inside the loop immediately terminates the loop when the total equals 0.
C.An if statement comparing the total to 0, followed by break, correctly implements the early exit.
D.A continue statement placed inside the loop would stop the entire scan when the total equals 0.
E.The condition for printing must be checked before the zero check, or zero totals could be printed.
AnswersB, C

The break statement exits the innermost enclosing loop at once, skipping any remaining iterations. Placing it inside an if that checks for a total of exactly 0 fulfills the requirement to stop scanning entirely at that point. Any totals after the zero, whether above 100 or not, are never examined, which is precisely the behaviour the script must exhibit.

Why this answer

Stopping a scan at a sentinel value is the classic use case for break, which exits the innermost loop immediately. Pairing it with an if that compares the current total to 0 gives the required early termination. The continue statement only skips to the next iteration, and using exceptions for ordinary control flow is discouraged, so those approaches fail to meet the requirement.

Exam trap

The trap here is treating continue as a way to stop a loop, when it merely skips the remainder of the current iteration and keeps going.

141
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

`range(3)` generates the integer sequence 0, 1, 2 — three values, starting at 0 and stopping before 3. The loop body executes once per generated value, so `print('Hi')` runs exactly three times, satisfying the stem's count 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.

142
MCQeasy

Which operator is used for integer division in Python?

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

The `//` operator performs floor division, returning the largest integer less than or equal to the true quotient. For positive integers this discards the fractional part, satisfying the stem's requirement for integer division. Unlike `/`, which always yields a float in Python 3, `//` preserves integer type when both operands are integers.

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.

143
MCQeasy

A programmer is writing a Python script to calculate the area of a circle. They write the following code: radius = 5 area = 3.14 * radius ** 2 print(area) What is the output of this code?

A.25
B.31.4
C.An error occurs because radius is an integer and cannot be used with exponentiation.
D.78.5
AnswerD

The expression 3.14 * radius ** 2 is evaluated as 3.14 * (5 ** 2) because the exponentiation operator ** has higher precedence than multiplication. 5 ** 2 equals 25, and 3.14 * 25 equals 78.5. The print statement outputs 78.5, which is the correct area calculation using the given approximation of pi.

Why this answer

The exponentiation operator ** has higher precedence than multiplication, so radius ** 2 is computed first, yielding 25. Then 3.14 * 25 equals 78.5, which is printed. This demonstrates correct operator precedence in Python and the use of the exponentiation operator for squaring a number.

Exam trap

The trap here is misapplying operator precedence by multiplying before exponentiating, which would yield a different result.

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

145
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 int() call raises a ValueError because 'abc' cannot be parsed as base-10 integer, so execution jumps straight to the except block, printing the error message. The finally block then runs regardless, printing "Done". This satisfies the stem's requirement that both the error text and "Done" appear in that order.

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

146
Multi-Selecthard

A developer is auditing loop constructs in a Python script. Which TWO statements about `break`, `continue`, `else`, and `range` are correct in Python? (Choose two.)

Select 2 answers
A.`break` exits only the current iteration and resumes with the next item.
B.A `while` loop always executes its body at least once, even if the condition is initially false.
C.`range(5)` produces the list `[0, 1, 2, 3, 4, 5]` when printed.
D.`continue` skips the rest of the current iteration and immediately re-evaluates the loop condition or fetches the next item.
E.A loop's `else` clause executes only if the loop finishes without hitting a `break`.
AnswersD, E

This correctly describes `continue`: it abandons the remaining statements in the current iteration and proceeds to the next one, re-checking the condition in a `while` loop or advancing the iterator in a `for` loop. It is often used to skip unwanted values without nesting the body inside a large `if` block, keeping the code flatter.

Why this answer

The `else` clause of a loop runs only on normal exhaustion, not after a `break`, which supports search idioms. `continue` ends the current iteration and moves to the next, re-evaluating or advancing as appropriate. The other statements misdescribe `break` as iteration-skipping, give `range` an inclusive upper bound, and claim `while` always runs once, all of which are incorrect for Python.

Exam trap

The trap here is assuming a loop's `else` runs regardless of how the loop ends, when a `break` actually suppresses it.

147
MCQmedium

A developer writes the following code and runs it without any error: x = 5 y = 2.0 z = x + y What is the value and type of z?

A.A TypeError is raised because int and float cannot be added
B.7, of type int
C.7.0, of type float
D.7.0, of type str
AnswerC

Python's arithmetic follows a numeric type hierarchy, and mixing an int with a float promotes the int to float before the operation. The addition of 5 and 2.0 therefore produces 7.0 as a float object. The type of the variable z is float, confirmed by calling type(z), which returns the float class.

Why this answer

When Python evaluates an arithmetic expression containing both an int and a float, it converts the integer to a float and produces a float result. Adding five and two point zero yields the float value seven point zero. The variable z therefore references a float object, which can be verified by examining type(z) in the interpreter.

Exam trap

The trap here is assuming the result keeps the integer type because the value looks whole, overlooking Python's automatic float promotion in mixed arithmetic.

148
MCQhard

A data analyst has a list `readings` of numeric sensor values and needs to build a new list `scaled` that contains each reading multiplied by 2, but only for readings that are positive. Negative and zero readings should be excluded. Which code correctly produces `scaled`?

A.scaled = [r * 2 for r in readings if r >= 0]
B.scaled = [r * 2 for r in readings if r > 0]
C.scaled = [r * 2 if r > 0 for r in readings]
D.scaled = [r for r in readings if r > 0] * 2
AnswerB

This list comprehension applies the filter r > 0 before including an element and then multiplies each qualifying reading by 2. Negative and zero values are excluded by the condition, and only positive readings appear in the new list. It is concise, correct, and uses standard Python list comprehension syntax with a filter clause.

Why this answer

The correct comprehension uses a filter clause after the for to include only positive readings, then multiplies each by 2 in the expression. This produces a new list containing doubled values for positive readings only, excluding negatives and zeros. It matches the analyst's specification and uses idiomatic Python syntax.

Exam trap

The trap here is mixing up the filter condition with the transformation, or using >= instead of >, which would incorrectly include zero readings.

149
MCQmedium

A validation script defines a list named flags containing boolean values. The script must determine whether every flag is True and print 'All clear' only in that case; otherwise it should print 'Check needed'. Which code fragment implements this logic correctly?

A.if flags: print('All clear') else: print('Check needed')
B.if any(flags): print('All clear') else: print('Check needed')
C.if all(flags): print('All clear') else: print('Check needed')
D.if flags == True: print('All clear') else: print('Check needed')
AnswerC

The built-in all function returns True when every element in the iterable is truthy. For a list of booleans, that means all values must be True, so the conditional prints the correct message for both the all-True and any-False cases.

Why this answer

Determining that every element is True requires a check that inspects all elements and fails if any is falsy. The built-in all function does exactly that, returning True only when every element is truthy and False otherwise, which maps directly onto the two required messages.

Exam trap

The trap here is confusing any with all or assuming that a non-empty list of booleans is itself a reliable truth test for all values being True.

150
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

The dictionary comprehension iterates over each element in `names`, binding `name` to the string and computing `len(name)` as its value, producing `{'Alice': 5, 'Bob': 3, 'Charlie': 7}`. This satisfies the requirement to map every name to its length in a single expression, unlike `map` or `zip` alternatives.

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.

Page 1

Page 2 of 7

Page 3

All pages