Courseiva

Certified Entry-Level Python Programmer PCEP (PCEP) — Questions 1–75

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

Page 1 of 7

Page 2
1
MCQhard

You are a junior developer at a logistics company. Your team maintains a Python script that processes daily shipment data from a CSV file. The script reads the file, computes total weight per shipment, and writes results to a new CSV. Recently, the script started crashing sporadically with a 'ValueError: invalid literal for int() with base 10: 'NULL''. The CSV file sometimes contains the string 'NULL' in the weight column for missing values. The current code reads the weight column as: weight = int(row['weight']). Your team lead wants a robust fix that handles missing data gracefully without crashing, and also logs the line number for any problematic rows for later review. Which of the following approaches best meets these requirements?

A.Use the string method .isdigit(): if row['weight'].isdigit(): weight = int(row['weight']); else: weight = 0; no logging.
B.Read the entire file into a list, then use a list comprehension to convert weights: weights = [int(w) if w != 'NULL' else 0 for w in rows] without logging.
C.Wrap the int conversion in a try-except block: try: weight = int(row['weight']); except ValueError: weight = 0; log the line number using a counter variable.
D.Add a check: if row['weight'] != 'NULL': weight = int(row['weight']); else: weight = 0; and log a warning. Do not use try-except.
AnswerC

Catching ValueError around int() lets the script substitute a default weight for 'NULL' entries and continue processing, while a counter tracks the offending line for later review. This satisfies both the graceful-handling and line-logging constraints without halting the whole run.

Why this answer

It uses a try-except block to catch the ValueError when int() fails on 'NULL', sets weight to 0 as a fallback, and logs the line number using a counter variable. This approach handles any unexpected non-numeric string (not just 'NULL'), making it robust against future data anomalies, and satisfies the requirement to log problematic rows for review.

Exam trap

The PCEP exam often tests the distinction between LBYL (Look Before You Leap) and EAFP (Easier to Ask for Forgiveness than Permission) paradigms, and the trap here is that candidates choose a seemingly simple string check (like Option D) without realizing it fails for any unexpected invalid input, while the try-except approach is the recommended Pythonic solution for robust error handling.

How to eliminate wrong answers

Option A is wrong because .isdigit() returns False for negative numbers, floats, and empty strings, and it does not log the line number, failing the logging requirement. Option B is wrong because reading the entire file into a list and using a list comprehension without logging ignores the requirement to log line numbers for problematic rows, and it assumes all non-'NULL' values are valid integers, which is not guaranteed. Option D is wrong because it only checks for the literal string 'NULL', missing other invalid literals like empty strings or 'N/A', and while it logs a warning, it does not use a counter variable to log the specific line number as required.

2
Multi-Selecthard

A Python programmer is analyzing the results of several expressions. Which TWO of the following expressions evaluate to a float value? (Choose two.)

Select 2 answers
A.4 + 2
B.4.0 // 2
C.4 / 2
D.4 * 2
E.4 // 2
AnswersB, C

The floor division operator // returns a float if either operand is a float. Here, 4.0 is a float, so 4.0 // 2 yields 2.0, which is a float. Even though the operation is floor division, the presence of a float operand forces the result to be a float. Thus, this expression evaluates to a float value.

Why this answer

In Python, the / operator always returns a float, so 4 / 2 yields 2.0. Additionally, floor division // returns a float if either operand is a float, so 4.0 // 2 yields 2.0. The other expressions involve only integers and use operators that return integers when both operands are integers.

Thus, the expressions that evaluate to a float are 4 / 2 and 4.0 // 2.

Exam trap

The trap here is assuming that floor division always returns an integer, but when one operand is a float, the result is a float.

3
MCQhard

What is the output of the following code? print(type(3.0) == float)

A.<class 'bool'>
B.False
C.Error
D.True
AnswerD

The literal 3.0 is a floating-point number, so type(3.0) returns the float class object. Comparing that class object with float using == tests identity of the same built-in type, yielding True. This satisfies the stem's requirement to evaluate the expression's actual output.

Why this answer

The expression `type(3.0) == float` compares the result of `type(3.0)` (which is `<class 'float'>`) directly to the `float` class. In Python, `type()` returns the class object, and comparing it with `==` to the built-in class `float` yields `True` because they are the same object. Therefore, `print(True)` outputs `True`.

Exam trap

Python Institute often tests the distinction between `type()` returning a class object versus a string representation, and candidates mistakenly think `type(3.0)` returns the string `'float'`, leading them to choose `False` or `Error`.

How to eliminate wrong answers

Option A is wrong because `print()` outputs the value of the expression, not its type; the expression evaluates to `True`, which is a boolean, but the output is the string representation `True`, not `<class 'bool'>`. Option B is wrong because the comparison `type(3.0) == float` is `True`, not `False`; a common mistake is thinking `type()` returns a string like `'float'`, but it returns the actual class object. Option C is wrong because the code is syntactically valid and runs without any error; `type(3.0)` is a valid call, and comparing it with `==` to `float` is allowed.

4
MCQeasy

What does the following code print? x = 10 if x > 5: if x > 15: print("A") else: print("B") else: print("C")

A.No output
B.C
C.B
D.A
AnswerC

x equals 10, so the outer condition x > 5 is true and the inner block runs. The inner test x > 15 is false, so the else branch executes, printing B. The outer else is skipped entirely.

Why this answer

The code first checks if x > 5, which is true because x = 10. Then it checks if x > 15, which is false, so the else branch of the inner if-else executes, printing 'B'. The outer else is skipped entirely.

Exam trap

Python Institute often tests the misconception that the outer else (printing 'C') will execute when the inner condition fails, but candidates must remember that the outer else only runs if the outer condition is false.

How to eliminate wrong answers

Option A is wrong because the code does produce output; the inner else branch executes. Option B is wrong because 'C' would only print if the outer condition x > 5 were false, but it is true. Option D is wrong because 'A' would print only if x > 15 were true, but x = 10 is not greater than 15.

5
Multi-Selectmedium

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

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

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

Why this answer

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

Exam trap

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

6
MCQhard

A function sometimes returns None. Which expression correctly checks if the return value is not None?

A.if not val is None:
B.if val != None:
C.if val is not None:
D.if val:
AnswerC

The identity operator is not None compares the object reference against the None singleton, which is the correct idiom for checking a missing return value. Equality operators can be overridden by custom __eq__ methods, so 'is not' is safer.

Why this answer

The `is not` operator is the proper way to check identity inequality in Python. Since `None` is a singleton, comparing with `is not` ensures you are checking whether the value is literally the `None` object, which is the recommended and most readable approach for `None` checks.

Exam trap

Python Institute often tests the distinction between identity (`is`) and equality (`==`) operators, and the trap here is that candidates mistakenly use `!= None` (value comparison) instead of `is not None` (identity comparison), or confuse truthiness checks with `None` checks.

How to eliminate wrong answers

Option A is wrong because `if not val is None:` is syntactically valid but confusing and non-idiomatic; it actually means `if not (val is None):` due to operator precedence, which is equivalent to `if val is not None:` but is discouraged for readability. Option B is wrong because `if val != None:` uses value equality (`!=`) instead of identity (`is not`); while it often works due to Python's implementation, it can fail if the object's `__eq__` method is overridden to return `True` when compared to `None`. Option D is wrong because `if val:` checks truthiness, not whether the value is `None`; many falsy values (e.g., `0`, `False`, empty list) would cause the condition to be `False` even though they are not `None`.

7
MCQeasy

A developer writes the following code: result = (5 + 3) * 2 ** 3 // 4. What is the value of result?

A.8
B.16
C.13
D.64
AnswerB

Parentheses force 5 + 3 to evaluate first, giving 8. Exponentiation binds tighter than floor division, so 2 ** 3 yields 8, and 8 * 8 gives 64. Floor division by 4 then returns 16, satisfying Python's precedence order of parentheses, exponent, multiplication, then floor division.

Why this answer

Python follows the operator precedence rules: exponentiation (**) is evaluated before multiplication and division, and multiplication/division are evaluated before addition/subtraction. The expression evaluates as: 2 ** 3 = 8, then (5 + 3) = 8, then 8 * 8 = 64, then 64 // 4 = 16. The integer division (//) yields an integer result of 16.

Exam trap

Python Institute often tests the combination of exponentiation and floor division with parentheses, where candidates forget that ** binds tighter than * and //, leading them to compute (5+3)*2 = 16, then 16**3 = 4096, then 4096//4 = 1024, or they ignore the // and just compute 8*8=64.

How to eliminate wrong answers

Option A is wrong because it assumes the expression is evaluated left-to-right without precedence, e.g., (5+3)=8, then 8*2=16, then 16**3=4096, then 4096//4=1024, which is not 8; or it might incorrectly compute 2**3=8, then 8//4=2, then 8*2=16, but then subtract something incorrectly. Option C is wrong because it likely results from misapplying precedence, e.g., computing (5+3)=8, then 2**3=8, then 8*8=64, then 64/4=16.0 (float) but then rounding or truncating incorrectly to 13, or mixing // with / in a wrong order. Option D is wrong because it ignores the floor division (//) entirely, computing 8 * 8 = 64 and stopping, or it incorrectly treats // as exponentiation again.

8
Multi-Selecteasy

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

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

Valid: range creates sequence, list() converts to list.

Why this answer

`list(range(1, 4))` creates a list from the range object that generates numbers 1, 2, and 3 (the `range` function stops before the stop value 4). This is a common Python idiom for converting a range into a list.

Exam trap

Python Institute often tests the distinction between list literals (square brackets) and tuple literals (parentheses), and the requirement for commas as separators, to catch candidates who confuse syntax from other languages or misuse punctuation.

9
MCQmedium

A logistics coordinator stores shipment weights in a list `weights = [12, 18, 7, 25]`. She needs to find the average weight of all shipments. Which code snippet correctly computes and prints the average?

A.print(total(weights) / len(weights))
B.print(mean(weights) / len(weights))
C.print(sum(weights) // len(weights))
D.print(sum(weights) / len(weights))
AnswerD

This uses the built-in `sum()` to total all elements and divides by the count from `len()`, yielding the arithmetic mean. For the given list, the sum is 62 and the length is 4, so the average is 15.5. This is the standard, concise Python approach for averaging a list of numbers.

Why this answer

The average is calculated by dividing the sum of all elements by the number of elements. The built-in `sum()` and `len()` functions provide these values directly, and the `/` operator returns a float result. The other options either use incorrect functions or perform integer division, which loses the fractional part.

Exam trap

The trap here is confusing the floor division operator `//` with true division `/`, leading to a truncated result instead of the exact average.

10
Multi-Selectmedium

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

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

keys() returns a view object of the dictionary's keys and is a genuine built-in dict method. It satisfies the question's requirement for a valid dictionary method, distinguishing it from list-only operations such as append or index.

Why this answer

The `keys()` method returns a view object displaying all keys in a dictionary, and `values()` returns a view object of all values. Both are built-in dictionary methods in Python, making them valid for the PCEP exam.

Exam trap

The exam often tests candidates by including method names from other languages (like Java's `keyset()` or `entries()`) to exploit confusion between Python and Java dictionary APIs.

11
MCQhard

An inventory script defines `def add_stock(item, quantity, *restock_dates):` and is called as `add_stock('bolt', 40, '2024-01-05', '2024-02-11')`. Inside the function, the developer wants to count how many restock dates were supplied. Which expression correctly reports that count?

A.len(restock_dates[0])
B.len(restock_dates)
C.restock_dates.length
D.restock_dates.count
AnswerB

A parameter prefixed with an asterisk collects any extra positional arguments into a tuple. Here restock_dates becomes ('2024-01-05', '2024-02-11'), so len(restock_dates) returns 2. Because it is a tuple, it supports len, indexing, and iteration, which is exactly how variadic functions inspect the surplus arguments they received.

Why this answer

The starred parameter packs all surplus positional arguments into a tuple, so the number of restock dates equals the length of that tuple. Calling the built-in len on the packed tuple gives the exact count of extra arguments received, while indexing or attribute-style length access either measures the wrong thing or fails outright.

Exam trap

The trap here is treating the packed parameter as if it had a length attribute or as if measuring one element summarized the whole collection, when only len on the tuple gives the total count.

12
MCQeasy

A developer writes a function to calculate the average of a list of numbers, but the function sometimes returns a wrong result when the list contains non-numeric values. What is the best way to handle this?

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

Validating every element with a numeric type check before summing prevents silent wrong results from strings or None. Raising TypeError signals invalid input explicitly, satisfying the requirement to handle non-numeric values rather than returning an incorrect average.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

13
MCQhard

A program contains a nested while loop. The inner loop should run as long as a condition is True, but the outer loop should stop after 3 iterations. Which code structure is correct? (Assume the inner loop condition is inner < 5.)

A.for outer in range(3): inner = 0 while inner < 5: # do something inner += 1
B.outer = 0 while outer < 3: for inner in range(5): # do something outer += 1
C.outer = 0 while outer < 3: inner = 0 while inner < 5: # do something outer += 1 inner += 1
D.outer = 0 while outer < 3: inner = 0 while inner < 5: # do something inner += 1 outer += 1
AnswerD

Correct; outer increments after inner loop completes.

Why this answer

Ly implements a nested while loop where the inner loop runs while `inner < 5` and the outer loop runs while `outer < 3`. The inner loop increments `inner` to control its own termination, and the outer loop increments `outer` after the inner loop completes, ensuring exactly 3 iterations of the outer loop. This matches the requirement that the outer loop stops after 3 iterations while the inner loop runs as long as its condition is True.

Exam trap

Python Institute often tests the misconception that incrementing a loop counter inside a nested loop will correctly control both loops, when in fact it causes the outer loop to terminate prematurely, as seen in options B and C.

How to eliminate wrong answers

Option A is wrong because it uses a `for` loop for the outer loop, not a `while` loop as specified in the question (the outer loop should be a `while` loop, not a `for` loop). Option B is wrong because it increments `outer` inside the inner `for` loop, causing the outer `while` loop to terminate prematurely after the first inner iteration (since `outer` becomes 3 after one pass through the inner loop). Option C is wrong because it increments `outer` inside the inner `while` loop, which also causes the outer loop to terminate early (after the first inner iteration) and disrupts the intended 3 outer iterations.

14
MCQmedium

A developer needs to store the result of dividing two numbers, a/b, but only if b is not zero. They write: result = a / b if b != 0 else 'undefined'. What is the data type of result when b is zero?

A.float
B.NoneType
C.bool
D.str
AnswerD

When b equals zero, the conditional expression selects the literal 'undefined', a string, so result holds str. The division branch is never evaluated, avoiding ZeroDivisionError; the ternary returns whichever operand's type applies, and here that operand is textual.

Why this answer

When `b` is zero, the expression `a / b if b != 0 else 'undefined'` evaluates to the string literal `'undefined'`. Therefore, the variable `result` is assigned a value of type `str` (string). The conditional expression explicitly returns a string in the else branch, making option D correct.

Exam trap

Python Institute often tests the ternary conditional expression to see if candidates mistakenly think the else branch returns a special 'undefined' value (like in JavaScript) instead of recognizing it as a plain Python string literal.

How to eliminate wrong answers

Option A is wrong because a float is returned only when the division occurs (b != 0); when b is zero, no division happens, so no float is produced. Option B is wrong because NoneType would require the expression to evaluate to `None`, but the else clause explicitly returns the string `'undefined'`, not the Python `None` object. Option C is wrong because a bool would require the expression to evaluate to `True` or `False`, but the else clause returns a string, not a boolean.

15
Matchingmedium

Match each Python control flow statement to its purpose.

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

Concepts
Matches

Exits the current loop immediately

Skips the rest of the current iteration and goes to the next

Does nothing; used as a placeholder

Short for else-if; checks another condition

Executes a block when no previous condition is true

Why these pairings

The correct matches: break exits the loop, continue skips to next iteration, pass does nothing, else runs after normal loop completion. Common confusions include swapping break and continue, or confusing else with pass.

16
Multi-Selecthard

Which THREE of the following statements about Python operators are true?

Select 3 answers
A.The not operator is a logical operator that negates a condition.
B.The // operator performs floor division.
C.The ** operator is the bitwise XOR operator.
D.The / operator always returns an integer if both operands are integers.
E.The % operator returns the remainder of division.
AnswersA, B, E

The `not` operator is a logical (Boolean) operator that inverts the truth value of its operand, returning `True` for a falsy operand and `False` for a truthy one. This directly satisfies the stem's requirement for a true statement about Python operators, as `not` is one of the three logical operators alongside `and` and `or`.

Why this answer

Option A is correct because 'not' is Python's logical negation operator, returning True for a falsy operand and False for a truthy one, so it negates a condition. Option B is correct because '//' performs floor division, dividing operands and rounding the result down to the nearest integer (e.g., 7 // 2 == 3, and -7 // 2 == -4). Option E is correct because '%' is the modulo operator, returning the remainder of integer or float division (e.g., 7 % 3 == 1).

Option C is wrong because '**' is the exponentiation (power) operator, while bitwise XOR is '^'. Option D is wrong because '/' performs true division in Python 3 and always returns a float, even when both operands are integers (e.g., 4 / 2 == 2.0).

Exam trap

Python Institute often tests the Python 3-specific change that the `/` operator always returns a float, trapping candidates who remember the Python 2 behavior where `/` performed integer division on integers.

17
MCQeasy

A list of numbers is defined as nums = [1, 2, 3, 4, 5]. Which expression returns the last element?

A.nums[5]
B.nums[-1]
C.nums[0]
D.nums[-2]
AnswerB

Negative indexing counts from the end of the sequence, so nums[-1] refers to the final element, 5. This satisfies the stem's requirement for retrieving the last element without computing its index from the list length.

Why this answer

Python uses zero-based indexing, so the first element is at index 0 and the last element is at index -1. Negative indices count from the end of the list, so nums[-1] directly accesses the last element (5) without needing to know the list length.

Exam trap

The trap here is that candidates often forget Python's zero-based indexing and mistakenly think the last element is at index equal to the list length (e.g., nums[5]), or they confuse negative indexing and pick nums[-2] thinking it refers to the last element.

How to eliminate wrong answers

Option A is wrong because it attempts to access index 5, which is out of range for a list of length 5 (valid indices are 0 through 4), and will raise an IndexError. Option C is wrong because nums[0] returns the first element (1), not the last. Option D is wrong because nums[-2] returns the second-to-last element (4), not the last.

18
MCQmedium

A program uses a for loop to double each element in a list: numbers = [1, 2, 3, 4, 5]; for num in numbers: num = num * 2. After execution, numbers remains unchanged. Why?

A.Reassigning num does not modify the original list element; you need to modify via index.
B.The assignment creates a new list, leaving the original unchanged.
C.Lists are immutable; their elements cannot be changed.
D.The variable num is a copy of the list element.
AnswerA

Reassigning `num` only rebinds the loop variable to a new integer object; it never writes back into the list. Integers are immutable, so no in-place mutation occurs. The stem's constraint — doubling every element — requires indexed assignment, such as `numbers[i] = numbers[i] * 2`, to alter the list itself.

Why this answer

In Python, the loop variable `num` is a reference to each element in the list, but reassigning `num` (e.g., `num = num * 2`) merely rebinds the local variable to a new integer object; it does not modify the original list element. To change the list in place, you must access elements by their index, such as `numbers[i] = numbers[i] * 2`.

Exam trap

The PCEP exam often tests the misconception that the loop variable is a mutable alias for the list element, leading candidates to believe reassigning it will update the list, when in fact it only rebinds the local variable.

How to eliminate wrong answers

Option B is wrong because the assignment `num = num * 2` does not create a new list; it only rebinds the loop variable to a new integer, leaving the original list object untouched. Option C is wrong because lists in Python are mutable; their elements can be changed via index assignment, unlike tuples or strings which are immutable. Option D is wrong because `num` is not a copy of the list element; it is a reference to the same object, but integers are immutable, so reassignment creates a new object without affecting the list.

19
MCQeasy

A beginner writes: x = '10'; y = 20; print(x + y). What happens?

A.Raises TypeError
B.Prints 30
C.Prints 10 + 20
D.Prints 1020
AnswerA

Python does not implicitly convert between str and int, so adding the string '10' to the integer 20 raises TypeError. This satisfies the question by identifying the runtime error produced when concatenation and addition are mixed across incompatible types.

Why this answer

Python's type system does not allow implicit concatenation of a string and an integer. The variable `x` is a string (`'10'`), and `y` is an integer (`20`). The `+` operator with these types triggers a `TypeError: unsupported operand type(s) for +: 'int' and 'str'` (or vice versa), as Python refuses to guess the programmer's intent.

Exam trap

The trap here is that candidates often expect Python to behave like JavaScript or PHP, which implicitly coerce types, but Python strictly requires explicit type conversion for mixed-type operations.

How to eliminate wrong answers

Option B is wrong because it assumes Python will implicitly convert the string to an integer and perform numeric addition, which Python does not do for mixed types. Option C is wrong because it treats the `+` operator as a literal string concatenation in the output, but Python evaluates expressions, not printing the source code. Option D is wrong because it assumes Python will implicitly convert the integer to a string and concatenate them as `'10' + '20'` → `'1020'`, but Python raises a TypeError instead of performing implicit type coercion.

20
MCQmedium

A developer writes: num = input('Enter a number: '); result = num * 2; print(result). If the user enters 5, what is the output?

A.Error: cannot multiply string by int
B.10
C.'5' * 2
D.55
AnswerD

`input()` returns a string, so `num` holds `'5'`, not the integer 5. Multiplying a string by 2 repeats it, giving `'55'`, which `print()` outputs without quotes. The stem's constraint is that no `int()` conversion is applied before the multiplication.

Why this answer

The `input()` function always returns a string. When the user enters '5', `num` is the string '5', not the integer 5. The `*` operator on a string performs repetition, so `'5' * 2` produces '55', which is printed as 55.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type when the user types digits, leading candidates to expect arithmetic multiplication instead of string repetition.

How to eliminate wrong answers

Option A is wrong because Python does not raise an error when multiplying a string by an integer; it performs string repetition. Option B is wrong because it assumes `input()` returns an integer, but it returns a string, so numeric multiplication does not occur. Option C is wrong because it shows the raw expression `'5' * 2` as output, but `print()` outputs the resulting string '55', not the expression.

21
MCQeasy

Which data type is the result of: value = 10 // 3?

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

Floor division with `//` discards the fractional part and returns an integer when both operands are integers, so `10 // 3` yields `3`, not `3.333...`. This satisfies the stem's requirement for the exact data type of the result, which is `int`.

Why this answer

The // operator in Python performs floor division, which divides the left operand by the right operand and returns the largest integer less than or equal to the result. Since both 10 and 3 are integers, the result is an integer (3), not a float. Therefore, the data type of value is int.

Exam trap

Python Institute often tests the distinction between / (true division returning float) and // (floor division returning int), trapping candidates who assume all division in Python returns a float.

How to eliminate wrong answers

Option A is wrong because floor division (//) with integer operands always returns an int, not a float; a float result would require the / operator (true division). Option B is wrong because the result is a numeric value, not a string; str would only be produced by explicit conversion or string concatenation. Option D is wrong because the result is a numeric integer, not a Boolean; bool would only be returned by comparison operators (e.g., ==, >) or logical operations.

22
Drag & Dropmedium

Arrange the steps to read data from a text file in Python.

Drag or tap steps into the slots.

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

Why this order

The correct sequence for reading data from a text file in Python is: first open the file using the open() function, then read its contents (e.g., with read() or readlines()), process the data as needed, and finally close the file with close(). Opening establishes a file handle, reading retrieves the data, processing uses it, and closing releases resources. Common mistakes include closing before processing, processing before reading, or reading before opening.

23
MCQeasy

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

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

Default parameters apply when an argument is omitted at call time. Calling `greet('Alice')` supplies only `name`, so Python binds `greeting` to its default value `'Hello'`, printing `Hello Alice`. The single positional argument satisfies `name`, leaving the optional parameter untouched.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

24
MCQmedium

A logistics coordinator tracks delivery statuses in a list of strings. The coordinator wants to build a new list containing only the statuses that are not equal to `"delivered"`, preserving the original order. Which code fragment produces the desired list `pending`?

A.pending = statuses.remove("delivered")
B.pending = [s for s in statuses if not "delivered"]
C.pending = [s for s in statuses if s != "delivered"]
D.pending = [s for s in statuses if s == "delivered"]
AnswerC

This list comprehension iterates every status, keeps only those whose value differs from `"delivered"`, and collects them in the original order. It is concise and equivalent to an explicit loop with a conditional append. Because the condition is evaluative rather than terminating, all non-delivered entries are retained regardless of position.

Why this answer

Selecting all entries that differ from a target value calls for a comprehension whose condition compares each element with `!=`. That preserves order and includes every non-matching status. Inverting the comparison keeps the wrong subset, `remove` mutates and returns `None`, and testing the literal's truthiness yields nothing at all.

Exam trap

The trap here is writing `not "delivered"` as if it compared a variable, when it actually negates a non-empty string literal.

25
MCQmedium

What does the following code print? text = 'Hello World'; print(text.replace('o', '0').upper())

A.hell0 w0rld
B.HELLO WORLD
C.HELL0 W0RLD
D.Hell0 W0rld
AnswerC

The `replace('o', '0')` method call runs first, swapping every lowercase 'o' for a zero, producing 'Hell0 W0rld'. The chained `.upper()` then converts all remaining characters to uppercase, yielding 'HELL0 W0RLD'. This satisfies the stem's requirement to print the transformed string, with digits unaffected by uppercasing.

Why this answer

The code first replaces all occurrences of 'o' with '0' in 'Hello World', resulting in 'Hell0 W0rld'. Then it applies the .upper() method, converting all characters to uppercase, yielding 'HELL0 W0RLD'. Therefore, the output is 'HELL0 W0RLD'.

Exam trap

PCEP often tests method chaining and the order of operations; candidates may forget that .upper() is applied after .replace(), or they may think .upper() only capitalizes the first letter (confusing it with .capitalize()).

How to eliminate wrong answers

Option A is wrong because it shows lowercase letters and the replacement, but the .upper() method is applied after replace, so the result should be uppercase. Option B is wrong because it shows 'HELLO WORLD' without the replacement of 'o' with '0'; the replace method changes the 'o's to '0's before uppercasing. Option D is wrong because it shows only the first letter capitalized, but .upper() converts the entire string to uppercase, not just the first character.

26
MCQmedium

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

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

The comprehension iterates x over range(3), giving 0, 1 and 2, and maps each to its square. The resulting dictionary pairs 0 with 0, 1 with 1 and 2 with 4, producing exactly {0:0, 1:1, 2:4}.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

27
Multi-Selectmedium

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

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

values returns a view of dictionary values.

Why this answer

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

Exam trap

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

28
MCQmedium

You are a developer in a company that runs a Python script daily to generate reports. The script uses the os module to list files in a directory and process each. Recently, after a server migration, the script fails with 'PermissionError: [Errno 13] Permission denied'. The script runs under a service account that has read/write access to most folders, but the migration changed the permissions on certain subdirectories. The error is intermittent, occurring only for some files. You need to fix the script to continue processing other files even if one fails. Which approach should you take?

A.Use a try-except block inside the loop to catch PermissionError for each file and continue.
B.Wrap the entire processing loop in a try-except that catches all exceptions and passes silently.
C.Before processing each file, use os.access() to check permissions and skip if not accessible.
D.Ask the server administrator to grant full permissions to the service account on all directories.
AnswerA

Wrapping each file operation in try-except catches PermissionError per iteration, so the loop continues processing remaining files instead of aborting. This satisfies the stem's requirement to handle intermittent permission failures on certain subdirectories while still processing the rest.

Why this answer

By placing a try-except block inside the loop that catches PermissionError specifically, the script can skip the problematic file and continue processing the remaining files. This approach handles the intermittent permission errors gracefully without halting the entire script. Option B is wrong because catching all exceptions silently would mask other critical errors (e.g., bugs in the processing logic).

Option C is wrong because os.access() checks may not fully reflect actual runtime permissions due to race conditions and platform-specific behavior, and it requires additional calls that could still fail. Option D is wrong because it relies on external action and does not address the need for the script to be resilient to such errors.

29
MCQhard

A script uses the input() function to get a user's age: age = input('Enter age: '). Later it computes age > 18. This raises a TypeError. What is the root cause?

A.The input() function cannot read numbers.
B.The variable age is automatically converted to int.
C.The variable age is a string, not an integer.
D.The comparison operator > is not valid for strings.
AnswerC

input() always returns a string in Python 3, so age holds text like "18". Comparing a str with an int using > raises TypeError, since Python won't implicitly coerce types. Converting with int(age) before the comparison resolves it.

Why this answer

The `input()` function in Python always returns a string, regardless of what the user types. When the user enters their age, the variable `age` holds a string like '25', not an integer. Comparing a string to an integer with the `>` operator raises a `TypeError` because Python does not automatically convert strings to numbers for comparison.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type when the user types a number, or that Python automatically converts strings to integers for comparison, leading candidates to overlook the need for explicit type conversion.

How to eliminate wrong answers

Option A is wrong because the `input()` function can read numbers, but it reads them as strings — it does not convert them to numeric types. Option B is wrong because the variable `age` is not automatically converted to `int`; Python requires explicit conversion using `int()` or `float()`. Option D is wrong because the `>` operator is valid for strings (it performs lexicographic comparison), but the error arises from comparing a string to an integer, not from the operator being invalid for strings.

30
MCQeasy

A developer is writing a Python script that should keep prompting for a password until the user enters the correct one. The script must not run forever if the user never guesses correctly, so it should give up after 5 attempts. Which loop construct is most appropriate for this scenario?

A.A for loop that iterates over the characters of the password string, comparing each character.
B.A for loop that iterates over range(5), checking the password inside and breaking when correct.
C.A while True loop with no break statement, relying on the password check to terminate.
D.A while loop that continues as long as the entered password is incorrect, with no attempt counter.
AnswerB

A for loop over range(5) runs exactly five times, providing a natural attempt limit. Inside, an if statement can compare the input to the stored password and break early when it matches, so the loop stops as soon as the correct value is entered, satisfying both the retry and the give-up-after-five requirement without any manual counter management.

Why this answer

The requirement combines a fixed maximum number of attempts with the possibility of stopping early on success. A for loop over range(5) supplies the exact bound of five iterations, and a break inside ends the loop as soon as the password matches. The other constructs either loop forever when the user keeps failing or do not model repeated input attempts at all.

Exam trap

The trap here is assuming that a while loop checking the password is equivalent to a bounded retry loop, when in fact it can run forever if the password is never correct.

31
MCQmedium

A developer writes a function to update a configuration dictionary: def update_config(config, key, value): config[key] = value; return config. They call it as: my_config = {'debug': False}; result = update_config(my_config, 'debug', True). What is the value of my_config after the call, and why?

A.my_config remains {'debug': False} because integers and booleans are immutable and passed by value.
B.A TypeError is raised because dictionaries cannot be modified inside a function.
C.my_config becomes {'debug': True} only if the function returns the dictionary and the caller reassigns it.
D.my_config becomes {'debug': True} because the dictionary is passed by reference and modified in place.
AnswerD

Dictionaries in Python are mutable objects. When passed to a function, the parameter config refers to the same dictionary object as my_config. The statement config[key] = value mutates that shared object, so the caller sees the change. No copy is made unless explicitly requested. Thus my_config now maps 'debug' to True, and result also refers to the same updated dictionary.

Why this answer

Because dictionaries are mutable and passed into functions by object reference, assigning to a key inside the function updates the caller's dictionary. The original object is modified in place, so the change is visible outside the function without any return or reassignment. This behavior is central to Python's argument-passing semantics for mutable types.

Exam trap

The trap here is assuming that because the value True is immutable, the dictionary cannot change, when mutability of the container is what matters.

32
MCQeasy

Refer to the exhibit. What is the most likely cause of this error?

A.Variable x is a string
B.Variable x is used before assignment
C.Variable x is an integer
D.Variable x is misspelled
AnswerB

Python raises UnboundLocalError when a name is assigned somewhere in a function, making it local throughout, yet read before that assignment executes. The traceback points to a read of x occurring before its first assignment on that code path.

Why this answer

The error message indicates that variable 'x' is being referenced before it has been assigned a value. In Python, using a variable that has not been defined yet raises a NameError. Option B correctly identifies this as the cause.

Exam trap

The PCEP exam often tests the distinction between a variable being undefined versus being of a certain type, tricking candidates into thinking the error is about type mismatch when it is actually about the variable not existing yet.

How to eliminate wrong answers

Option A is wrong because if x were a string, it would have been assigned a value (e.g., x = 'hello'), and no NameError would occur. Option C is wrong because if x were an integer, it would also have been assigned a value (e.g., x = 5), and no NameError would occur. Option D is wrong because a misspelled variable name would still raise a NameError, but the error message would reference the misspelled name, not 'x' — the question states the error is about variable x, so misspelling is not the issue.

33
Multi-Selecteasy

Which TWO of the following are valid Python data types?

Select 2 answers
A.real
B.str
C.array
D.int
E.char
AnswersB, D

str is a built-in Python data type representing text sequences, such as 'hello'. It satisfies the question's requirement to identify a valid data type, since str is one of Python's core immutable types alongside int, float and bool.

Why this answer

Option B (str) is correct because str is a built-in Python data type used to represent immutable sequences of Unicode characters, such as 'hello'. Option D (int) is correct because int is a built-in Python data type for arbitrary-precision integers, e.g., 42. Option A (real) is not a Python built-in type; Python uses float for floating-point numbers.

Option C (array) is not a built-in Python data type, though the array module provides an array class. Option E (char) is not a Python data type; Python represents single characters as strings of length 1.

Exam trap

Python Institute often tests the distinction between Python's built-in types and types from other languages or modules, so candidates mistakenly choose 'real' (from mathematics) or 'char' (from C/Java) because they assume Python uses the same terminology.

34
MCQeasy

A developer writes the following code: x = 5; y = 2; print(x // y). What is the output?

A.1
B.2
C.2.0
D.2.5
AnswerB

The // operator performs floor division, dividing 5 by 2 and rounding the result down to the nearest integer. Since both operands are integers, Python returns an int, and 2.5 floors to 2, matching the printed output.

Why this answer

The floor division operator (//) in Python returns the largest integer less than or equal to the result of the division. Since 5 divided by 2 equals 2.5, the floor is 2, and the result is an integer (int) because both operands are integers. Therefore, the output is 2.

Exam trap

Python Institute often tests the distinction between floor division (//) and true division (/), trapping candidates who confuse the two operators or forget that integer operands produce an integer result with //.

How to eliminate wrong answers

Option A is wrong because 1 would be the result of integer division only if the quotient were truncated toward zero (as in C/C++ with negative numbers) or if the calculation were 5 // 3; here 5 // 2 yields 2, not 1. Option C is wrong because floor division with two integers returns an integer, not a float; 2.0 would only appear if at least one operand were a float (e.g., 5.0 // 2). Option D is wrong because 2.5 is the result of true division (/) not floor division (//); the // operator always discards the fractional part.

35
Multi-Selecthard

Which THREE of the following statements about Python operators are correct?

Select 3 answers
A.The ** operator performs exponentiation.
B.The // operator performs floor division and returns an int if both operands are ints.
C.The / operator always returns a float.
D.The + operator can be used to concatenate strings and integers.
E.The % operator returns the quotient.
AnswersA, B, C

Python's arithmetic operator set includes ** for exponentiation, so 2 ** 3 evaluates to 8. This satisfies the stem's requirement for a correct operator statement, distinguishing it from operators such as ^, which performs bitwise XOR rather than raising to a power.

Why this answer

Option A is correct because in Python the ** operator is the exponentiation operator, so 2 ** 3 evaluates to 8. Option B is correct because // performs floor division, discarding the fractional part, and returns an int when both operands are ints (e.g., 7 // 2 gives 3). Option C is correct because the / operator performs true division and always returns a float, even for evenly divisible integers (e.g., 4 / 2 gives 2.0).

Option D is not correct because + cannot concatenate a string and an integer directly; doing so raises a TypeError unless the integer is converted with str(). Option E is not correct because % is the modulo operator and returns the remainder of a division, not the quotient.

Exam trap

Python Institute often tests the distinction between the / operator (always returns float) and the // operator (returns int when both operands are ints), and the misconception that % returns the quotient instead of the remainder.

36
MCQhard

A programmer needs a constant that identifies the maximum number of retry attempts for a network operation. The value must not change while the program runs. Which statement about naming and using this constant in Python is accurate?

A.Assigning it inside a function makes it permanently immutable
B.Naming it MAX_RETRIES signals by convention that it should not be reassigned
C.Wrapping the value in a tuple prevents any later change to the name
D.Declaring the name with the const keyword prevents reassignment
AnswerB

Python style guidance reserves all-uppercase names with underscores for constants, communicating intent to other developers. The interpreter does not enforce this, so reassignment remains technically possible, but the naming convention is the accepted way to mark a value as fixed. Tools and reviewers rely on this signal when reading code.

Why this answer

Python relies on naming conventions rather than keywords to express constants, and an all-uppercase identifier such as MAX_RETRIES is the standard signal that a value is intended to remain fixed. The language does not block reassignment, so the guarantee is social and stylistic, supported by linters and code review. Placing values in functions or containers changes scope or internal mutability but never prevents rebinding the name.

Exam trap

The trap here is expecting Python to enforce constants through a keyword or container, when only an uppercase naming convention communicates that intent.

37
MCQeasy

A junior developer writes a Python script to sum all numbers greater than 10 from a list. The code is: numbers = [5, 12, 8, 15, 3] total = 0 for num in numbers: if num > 10: total = total + 1 print(total) The output is 2, but the expected sum is 27 (12+15). Which change will produce the correct output?

A.Change `total = 0` to `total = []`
B.Change `total = total + 1` to `total += num`
C.Change `if num > 10:` to `if num >= 10:`
D.Change `for num in numbers:` to `for num in range(numbers):`
AnswerB

Replacing the increment with `total += num` accumulates each qualifying value rather than counting matches, satisfying the stem's requirement to sum numbers greater than 10. The `if num > 10` filter already isolates 12 and 15, so the accumulator yields 27 instead of the tally 2.

Why this answer

The original code increments `total` by 1 for each qualifying number, counting them instead of summing their values. Changing `total = total + 1` to `total += num` adds the actual number to the accumulator, producing the correct sum of 12 + 15 = 27.

Exam trap

The trap here is that candidates often confuse counting with summing — they see `total = total + 1` and think it's accumulating values, but it actually increments by a constant, not by the variable `num`.

How to eliminate wrong answers

Option A is wrong because changing `total = 0` to `total = []` makes `total` a list, and `total + 1` would cause a TypeError (cannot concatenate list and int). Option C is wrong because changing `if num > 10:` to `if num >= 10:` would include the number 10 (if present), but the list has no 10, so it does not fix the core issue of counting instead of summing. Option D is wrong because `range(numbers)` is invalid — `range()` expects integer arguments, not a list; this would raise a TypeError.

38
Multi-Selecthard

Which two of the following are true about Python lists? (Choose two.)

Select 2 answers
A.Lists can contain elements of different data types.
B.Lists can be used as dictionary keys.
C.Lists are indexed starting from 1.
D.Lists are immutable.
E.The len() function returns the number of elements.
AnswersA, E

Python lists are heterogeneous: a single list may hold integers, strings, floats and even nested lists together, because elements are references without a declared type. This satisfies the statement that lists accept elements of differing data types.

Why this answer

Option A is correct because Python lists are heterogeneous ordered collections, so a single list may hold elements of different data types (e.g., [1, 'two', 3.0, True]) without any type restriction. Option E is correct because the built-in len() function returns the number of elements in a list, such as len([10, 20, 30]) returning 3. Option B is incorrect because lists are mutable and therefore unhashable, so they cannot be used as dictionary keys (a TypeError is raised).

Option C is incorrect because Python uses zero-based indexing, so the first element is at index 0, not 1. Option D is incorrect because lists are mutable: elements can be added, removed, or reassigned in place via methods like append(), remove(), or item assignment.

Exam trap

The traps here include confusing list mutability with immutability, assuming indexing starts from 1, and mistakenly believing lists can be used as dictionary keys.

39
MCQmedium

A developer writes: total = 2 ** 3 + 4. What is the value of total?

A.16
B.12
C.14
D.10
AnswerB

Exponentiation binds tighter than addition, so 2 ** 3 evaluates first to 8, then 8 + 4 yields 12. The stem's expression therefore assigns 12 to total, not 14 as left-to-right evaluation would wrongly suggest.

Why this answer

In Python, the exponentiation operator (**) has higher precedence than addition (+). Therefore, 2 ** 3 is evaluated first, yielding 8. Then 8 + 4 equals 12.

Option B is correct.

Exam trap

Python Institute often tests operator precedence by combining exponentiation with addition, trapping candidates who mistakenly evaluate left-to-right or confuse ** with multiplication.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes that addition is performed before exponentiation, computing 2 ** (3 + 4) = 2 ** 7 = 128, or perhaps misinterprets the expression as (2 ** 3) * 2 = 16. Option C is wrong because it likely results from a miscalculation such as 2 ** 3 = 6 (instead of 8) plus 4 = 10, or from misapplying operator precedence. Option D is wrong because it represents the result of 2 * 3 + 4 = 10, confusing the exponentiation operator with multiplication.

40
MCQmedium

A developer is writing a function that accepts a dictionary of student names and their scores. The function should return the name of the student with the highest score. If the dictionary is empty, it should return `None`. Which code snippet correctly implements this?

A.def top_student(scores): if len(scores) == 0: return None return max(scores.items())
B.def top_student(scores): return max(scores.values())
C.def top_student(scores): return max(scores)
D.def top_student(scores): if not scores: return None return max(scores, key=scores.get)
AnswerD

This function checks if the dictionary is empty and returns None. Otherwise, it uses max with the key argument set to scores.get, which retrieves the value for each key and returns the key with the highest value. This correctly identifies the top student.

Why this answer

To find the key with the maximum value in a dictionary, pass a key function to max that extracts the value for each key. Using `scores.get` as the key function achieves this. The empty check prevents a ValueError.

The other options either return the wrong element or fail on an empty dictionary.

Exam trap

The trap here is forgetting that iterating over a dictionary yields keys, so max without a key function compares keys, not values.

41
Multi-Selectmedium

Which THREE of the following expressions evaluate to the integer 1? (Select three.)

Select 3 answers
A.int(1.0)
B.2 // 2
C.True == 1
D.1 * 1.0
E.4 % 3
AnswersA, B, E

int() truncates a float toward zero, discarding the fractional part. Applying it to 1.0 yields the integer 1, satisfying the stem's requirement for an int result rather than a float. This is the explicit type-conversion route to the value 1.

Why this answer

Option A, int(1.0), is correct because Python's int() constructor truncates the float 1.0 toward zero, yielding the integer 1. Option B, 2 // 2, is correct because floor division of 2 by 2 produces the integer quotient 1. Option E, 4 % 3, is correct because the modulo operator returns the remainder of 4 divided by 3, which is the integer 1.

Option C, True == 1, evaluates to the Boolean True rather than the integer 1, even though True is numerically equal to 1 in Python. Option D, 1 * 1.0, evaluates to the float 1.0, not the integer 1, because multiplying an int by a float promotes the result to float.

Exam trap

The PCEP exam often tests the distinction between Boolean `True` and the integer `1`, and the fact that arithmetic with a float operand always yields a float, not an integer.

42
MCQmedium

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

A.1
B.0 2
C.0 1 2
D.0
AnswerB

`range(3)` yields 0, 1, 2. When `i` equals 1, `continue` skips the remaining loop body, so `print` never runs for that iteration. Values 0 and 2 are printed with a trailing space, producing `0 2`.

Why this answer

The for loop iterates over range(3), which produces values 0, 1, and 2. When i equals 1, the continue statement skips the rest of the loop body for that iteration, so print(i, end=' ') is not executed for i=1. Thus, only 0 and 2 are printed, separated by a space, giving output '0 2'.

Option B is correct.

Exam trap

The PCEP exam often tests the continue statement by having candidates forget that it skips the rest of the loop body for the current iteration, leading them to incorrectly include the skipped value in the output.

How to eliminate wrong answers

Option A is wrong because it suggests only 1 is printed, but the continue statement skips the print for i=1, so 1 is never output. Option C is wrong because it includes 1, which is skipped by the continue statement; the loop does not print all three values. Option D is wrong because it omits 2; the loop continues after the continue and prints 2 when i=2.

43
MCQhard

Consider code: def outer(): x = 1 def inner(): nonlocal x x = 2 inner() print(x) outer() What is printed?

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

The `nonlocal x` declaration binds `inner`'s assignment to the enclosing `outer` function's variable, not a new local one. So `x = 2` mutates the same cell that `print(x)` reads after `inner()` returns, satisfying the stem's requirement that the enclosing scope's value be updated. Output is 2.

Why this answer

The `nonlocal` declaration inside `inner()` binds the variable `x` to the `x` defined in the enclosing `outer()` function. When `inner()` assigns `x = 2`, it modifies that outer `x`, so after `inner()` returns, `print(x)` in `outer()` outputs 2.

Exam trap

The PCEP exam often tests the distinction between `nonlocal` and `global`, and the trap here is that candidates mistakenly think `nonlocal` is unnecessary or causes an error, or they assume the inner assignment creates a separate local variable that does not affect the outer scope.

How to eliminate wrong answers

Option B is wrong because it assumes `inner()` creates a separate local variable `x` without `nonlocal`, but the `nonlocal` keyword explicitly links `x` to the enclosing scope, so the assignment overwrites the outer `x` from 1 to 2. Option C is wrong because `nonlocal x` is valid in a nested function when `x` exists in an enclosing (but non-global) scope; no `SyntaxError` or `NameError` occurs. Option D is wrong because `print(x)` executes and outputs an integer value, not `None`; `None` would only appear if `print` had no argument or the function returned `None` explicitly.

44
MCQmedium

A junior developer is writing a script to process a list of user IDs: ids = [101, 102, 103, 104]. The goal is to create a new list where each ID is increased by 10, without modifying the original list. The developer writes: new_ids = ids.append(10). However, the output shows None. The developer needs to correctly create the new list. Which code should the developer use to achieve this?

A.new_ids = [id + 10 for id in ids]
B.for i in range(len(ids)): ids[i] += 10; new_ids = ids
C.new_ids = ids + 10
D.new_ids = map(lambda x: x+10, ids)
AnswerA

A list comprehension builds a new list by evaluating id + 10 for each element, leaving ids untouched. The append method returns None and mutates in place, so it cannot satisfy the requirement of a separate transformed list.

Why this answer

It uses a list comprehension to create a new list by adding 10 to each element of the original list `ids`, leaving the original list unchanged. The `append()` method modifies the list in place and returns `None`, which is why the developer got `None`.

Exam trap

Python Institute often tests the distinction between methods that modify a list in place and return `None` (like `append()`, `sort()`) versus those that return a new object (like list comprehensions or `sorted()`), leading candidates to mistakenly assign the result of `append()` to a variable.

How to eliminate wrong answers

Option B is wrong because it modifies the original list `ids` in place (using `ids[i] += 10`) and then assigns the same list object to `new_ids`, so the original list is altered. Option C is wrong because `ids + 10` attempts to add an integer to a list, which raises a `TypeError` in Python (lists can only be concatenated with other lists). Option D is wrong because `map()` returns a map object (an iterator), not a list; to get a list, it must be wrapped in `list()`, e.g., `list(map(...))`.

45
MCQeasy

A developer writes code to calculate the area of a rectangle and prints it. The code is: length = 10 width = 5 area = length + width print('The area is', area) If the width is accidentally assigned a string '5', what error will occur?

A.ValueError
B.SyntaxError
C.TypeError
D.NameError
AnswerC

Assigning `'5'` makes `width` a string, so `length + width` attempts to add an integer and a string. Python does not implicitly coerce operands across these types, so the addition raises a TypeError before `print` runs. This satisfies the stem's scenario of accidental string assignment, where the failure occurs at the arithmetic operation itself.

Why this answer

In Python, adding an integer and a string is not a valid operation; it will raise a TypeError because Python cannot implicitly convert the string to an integer for arithmetic. Therefore, the code will raise a TypeError when executed.

Exam trap

The trap is that candidates may incorrectly assume that Python allows integer + string for arithmetic addition, but actually it raises a TypeError. The key is to recognize that Python does not perform implicit type conversion in this context.

How to eliminate wrong answers

Option A is wrong because ValueError is raised when a function receives an argument of the correct type but an inappropriate value (e.g., int('abc')), not for type mismatches in arithmetic. Option B is wrong because SyntaxError occurs when the Python parser encounters invalid syntax before execution, such as missing colons or unmatched parentheses; the code here is syntactically valid. Option D is wrong because NameError occurs when a variable name is not defined; both length and width are defined, so no NameError is raised.

46
Multi-Selecthard

A developer is writing a Python script and needs to create valid variable names. Which two of the following are valid variable names? (Choose two.)

Select 2 answers
A.2ndPlace
B.total_amount
C.my-var
D.for
E._value
AnswersB, E

total_amount uses only letters and an underscore, and does not start with a digit. It is a valid Python identifier. Underscores are commonly used to separate words in variable names, and this name follows all the rules for valid identifiers.

Why this answer

Valid Python identifiers must start with a letter or underscore, followed by letters, digits, or underscores, and cannot be keywords. _value and total_amount satisfy these rules, while my-var contains a hyphen, 2ndPlace starts with a digit, and for is a keyword.

Exam trap

The trap here is assuming that any name without spaces is valid, but identifiers cannot contain hyphens, start with digits, or be reserved keywords.

47
MCQeasy

A programmer wants to iterate over a list of strings and print each string in uppercase. Which of the following code snippets will accomplish this?

A.for item in my_list: print(item.upper)
B.for item in my_list: item.upper() print(item)
C.for i in my_list: print(my_list[i].upper())
D.for item in my_list: print(item.upper())
AnswerD

Iterating directly over my_list yields each string, and calling .upper() on it returns the uppercase form, which print outputs. This satisfies the requirement to print every string in uppercase without needing index tracking or a separate conversion step.

Why this answer

It correctly calls the `upper()` method on each string `item` in the list `my_list` and prints the result. The `upper()` method returns a new string with all characters converted to uppercase, and the `print()` function outputs that value to the console.

Exam trap

The trap here is that candidates often forget to include parentheses when calling a method (e.g., `item.upper` vs `item.upper()`), or they mistakenly think `upper()` modifies the string in place, leading them to print the original variable instead of the returned value.

How to eliminate wrong answers

Option A is wrong because `item.upper` without parentheses does not call the method; it merely references the method object, so nothing is printed. Option B is wrong because `item.upper()` returns a new string but does not modify `item` in place, and the subsequent `print(item)` prints the original lowercase string, not the uppercase version. Option C is wrong because `my_list[i]` attempts to use an integer index `i` as a list index, but `i` is a string from the list, not an integer; this will raise a `TypeError`.

48
MCQhard

Given the code: x = [1, 2, 3] y = x y.append(4) print(x) What is the output?

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

Assignment binds y to the same list object as x, not a copy. Calling append mutates that shared object in place, so the single list now holds four elements and printing x reflects the change.

Why this answer

In Python, variables hold references to objects, not the objects themselves. When `y = x` is executed, both `x` and `y` point to the same list object in memory. The `y.append(4)` method modifies that shared list in-place, so the change is reflected when `x` is printed, outputting `[1, 2, 3, 4]`.

Exam trap

Python Institute often tests the distinction between variable assignment and object copying, trapping candidates who mistakenly think `y = x` creates a separate copy of the list, leading them to choose option B.

How to eliminate wrong answers

Option A is wrong because no error occurs; the code runs successfully and produces a list. Option B is wrong because it assumes `y = x` creates a copy of the list, but Python does not copy objects on assignment; both variables reference the same mutable list. Option D is wrong because only one element (4) is appended, not two; the value 5 is never added.

49
MCQmedium

A Python programmer wants to determine whether the variable n is an even number greater than zero. Which expression correctly evaluates to True only when n is a positive even integer?

A.n % 2 == 0 and n > 0
B.n % 2 == 1 or n > 0
C.n / 2 == 0 and n > 0
D.n // 2 == 0 and n > 0
AnswerA

The modulo operation n % 2 yields the remainder when n is divided by 2. For even integers the remainder is 0, so n % 2 == 0 is True. The comparison n > 0 ensures the number is positive. Combining them with and requires both conditions to hold, which exactly matches the requirement of a positive even integer.

Why this answer

Even numbers leave a remainder of zero when divided by two, which the modulo operator % detects. The comparison n > 0 filters out zero and negative values. Joining these with the logical and operator yields True only for positive even integers.

Division and floor division do not test divisibility by two, and using or would accept odd values.

Exam trap

The trap here is confusing the division operator with the modulo operator, or using or instead of and, which would admit odd or non-positive numbers.

50
MCQhard

Given x = 5, which of the following assignments will cause a runtime error?

A.x **= 2
B.x -= 3
C.x //= 0
D.x += 2
AnswerC

Floor division by zero raises ZeroDivisionError at runtime, since Python cannot compute an integer quotient when the divisor is zero. The augmented assignment evaluates x // 0 immediately, satisfying the stem's condition of causing a runtime error rather than a syntax or name error.

Why this answer

Division by zero is undefined in Python, and the floor division assignment operator `//=` with a divisor of 0 raises a `ZeroDivisionError` at runtime. The other operators (`**=`, `-=`, `+=`) perform valid arithmetic on the integer 5 and do not cause errors.

Exam trap

The trap here is that candidates may mistakenly think any operator can handle zero as a divisor or confuse floor division with modulo, but The PCEP exam specifically tests that `//` with a zero divisor raises a runtime error, not a syntax error or silent failure.

How to eliminate wrong answers

Option A is wrong because `x **= 2` raises 5 to the power of 2, resulting in 25, which is a valid integer operation. Option B is wrong because `x -= 3` subtracts 3 from 5, yielding 2, a perfectly legal assignment. Option D is wrong because `x += 2` adds 2 to 5, producing 7, with no error.

Only division by zero triggers a runtime exception.

51
Multi-Selectmedium

A trainee is reviewing how Python 3 handles basic data types and type conversion in a small inventory script. Which TWO statements about Python's built-in numeric and string types are correct? (Choose two.)

Select 2 answers
A.Calling int('42') returns the integer 42, while int('4.2') raises a ValueError
B.The bool type is a distinct numeric type where True equals 1 and False equals 0 in arithmetic
C.The str type is mutable, so individual characters can be replaced by index assignment
D.The int type can represent arbitrarily large whole numbers limited only by available memory
E.The float type stores decimal values with exact precision for any fractional number
AnswersA, D

int accepts a string containing digits and optional sign, converting it to the matching integer. A string with a decimal point is not a valid integer literal, so conversion fails with ValueError. The correct path for such input is float('4.2') followed by int() if truncation is desired, making this statement an accurate description of the behaviour.

Why this answer

Python 3 integers grow to whatever size memory allows, so counters never silently overflow, and int() accepts only strings that look like whole numbers, rejecting anything with a decimal point. Together these behaviours shape how inventory quantities and parsed input are handled. Floats remain binary approximations, strings stay immutable, and bool is a subclass of int rather than a separate numeric family.

Exam trap

The trap here is assuming floats store decimal values exactly and that bool sits outside the integer hierarchy, when both assumptions contradict Python's actual type model.

52
MCQeasy

Refer to the exhibit. What is the cause of the error?

A.Using + on incompatible types (str and int)
B.Division by zero
C.Missing import statement
D.Variable not defined
AnswerA

The plus operator cannot concatenate a string with an integer; Python raises TypeError because the operands' types are incompatible. The exhibit's error stems from mixing str and int with +, which requires explicit conversion of the integer via str() before concatenation can succeed.

Why this answer

The error occurs because the `+` operator is being used between a string and an integer, which are incompatible types in Python. Python does not implicitly convert the integer to a string for concatenation; it raises a `TypeError: unsupported operand type(s) for +: 'str' and 'int'`.

Exam trap

Python Institute often tests the misconception that Python will automatically convert types (like JavaScript does), leading candidates to think the code will run without error, when in fact Python raises a TypeError for mixed-type `+` operations.

How to eliminate wrong answers

Option B is wrong because division by zero would raise a `ZeroDivisionError`, not a type-related error. Option C is wrong because no import statement is required for basic arithmetic or string operations in Python; the error is purely about type mismatch. Option D is wrong because the variable is defined (the error message would be `NameError` if it were not), and the actual error is a `TypeError` from using `+` on incompatible types.

53
MCQmedium

A program prints a greeting: name = input("Enter name: "); print("Hello, " + name + "!"). If user enters "Alice", what is output?

A.Hello, Alice!
B.Hello,Alice !
C.Hello,Alice!
D.Hello, Alice !
AnswerA

The `input()` function returns the entered text as a string, so `name` holds `"Alice"`. String concatenation with `+` joins `"Hello, "`, `"Alice"`, and `"!"` in sequence, producing exactly `Hello, Alice!` with no added spaces beyond those already inside the literals.

Why this answer

The `print` function concatenates the string literals and the variable `name` using the `+` operator exactly as specified. When the user enters "Alice", the expression `"Hello, " + name + "!"` becomes `"Hello, Alice!"` — the space after the comma is part of the first string literal, and the exclamation mark is part of the last string literal, producing the output exactly as shown in option A.

Exam trap

Python Institute often tests whether candidates notice the exact placement of spaces and punctuation in string literals, exploiting the common assumption that Python automatically adds spaces around concatenated values.

How to eliminate wrong answers

Option B is wrong because it shows a space after the exclamation mark (`Alice !`), but the code has no space before the exclamation mark in the string literal `"!"`. Option C is wrong because it omits the space after the comma (`Hello,Alice!`), but the first string literal `"Hello, "` includes a trailing space. Option D is wrong because it adds an extra space before the exclamation mark (`Alice !`), which is not present in the concatenation; the code joins `name` directly to `"!"` with no intervening space.

54
MCQeasy

What is the output of the following code? ```python print('Hello', 'World', sep='-') ```

A.HelloWorld
B.Hello - World
C.Hello World
D.Hello-World
AnswerD

Passing `sep='-'` overrides the default single-space separator that `print()` inserts between multiple arguments, so the two strings are joined by a hyphen instead. The output is therefore `Hello-World`, satisfying the stem's requirement to show the exact printed result.

Why this answer

The `print()` function's `sep` parameter specifies the separator between multiple arguments. By default, `sep` is a space, but here it is explicitly set to `'-'`, so the output joins 'Hello' and 'World' with a hyphen, producing 'Hello-World'. Option D is correct because the hyphen is placed directly between the two strings without any extra spaces.

Exam trap

The trap here is that candidates often assume the default space separator is used or misread the hyphen as a space, leading them to choose 'Hello World' instead of recognizing the explicit `sep='-'` override.

How to eliminate wrong answers

Option A is wrong because it omits the separator entirely, as if `sep=''` were used, but the default or specified separator is not empty. Option B is wrong because it adds spaces around the hyphen, which would only happen if the separator included spaces or if extra arguments were printed; the `sep` parameter does not add spaces unless they are part of the separator string. Option C is wrong because it uses a space as the separator, which is the default behavior, but the code explicitly overrides it with `sep='-`.

55
MCQeasy

A beginner writes: x = 10; y = 3; print(x // y). What is the output?

A.3
B.1
C.3.0
D.3.333
AnswerA

The // operator performs floor division, discarding the fractional part and rounding toward negative infinity. With 10 divided by 3, the true quotient is 3.333..., so floor division returns the integer 3, not 3.33 or 4.

Why this answer

The // operator in Python performs floor division, which returns the largest integer less than or equal to the result of the division. Since 10 divided by 3 equals 3.333..., the floor of that value is 3, and because both operands are integers, the result is an integer (3), not a float.

Exam trap

The PCEP exam often tests the distinction between floor division (//) and true division (/) by using integer operands, leading candidates to mistakenly expect a float result or to confuse floor division with truncation toward zero.

How to eliminate wrong answers

Option B is wrong because 1 would be the result of the modulo operation (10 % 3), not floor division. Option C is wrong because floor division with two integers returns an integer, not a float; 3.0 would require at least one operand to be a float (e.g., 10 // 3.0). Option D is wrong because 3.333 is the result of true division (10 / 3), not floor division.

56
MCQhard

A developer needs to store a large collection of unique user IDs (integers) and quickly check if a new ID already exists. Which data type is most appropriate for this task?

A.dict
B.list
C.set
D.tuple
AnswerC

A set stores unique elements and provides average O(1) membership testing, so checking whether an ID already exists is fast. Lists allow duplicates and require linear scans, making a set the appropriate structure for large collections of unique integers.

Why this answer

A set is the most appropriate data type because it stores unordered collections of unique elements and provides O(1) average-time complexity for membership testing using the `in` operator. This makes it ideal for quickly checking if a new user ID already exists without needing to manage keys or maintain order.

Exam trap

Python Institute often tests the misconception that a dict is required for any kind of lookup, when in fact a set is the correct choice for membership testing without associated data.

How to eliminate wrong answers

Option A is wrong because a dict stores key-value pairs, which adds unnecessary overhead when only the IDs themselves need to be stored and checked. Option B is wrong because a list requires O(n) linear search to check membership, which is inefficient for large collections. Option D is wrong because a tuple is immutable and does not support efficient membership testing; it also cannot be modified to add new IDs after creation.

57
MCQhard

A network engineer writes a script to validate IP addresses. The script checks each octet and prints 'Valid' if all octets are between 0 and 255, otherwise 'Invalid'. However, the script always prints 'Invalid' for valid IPs. The code uses a for loop with an else clause. Which logical error is likely?

A.The list of octets is not properly split
B.The condition uses 'or' instead of 'and'
C.The else clause is indented incorrectly
D.The for loop's else clause executes when the loop completes without break, but the engineer expects else to run when break occurs
AnswerD

Common misunderstanding of for-else; else runs on normal completion.

Why this answer

In Python, a `for` loop's `else` clause executes only when the loop completes normally (i.e., without hitting a `break`). The engineer likely intended the `else` to run when an invalid octet is found (triggering a `break`), but instead the `else` runs when all octets are valid and the loop finishes without breaking, causing the script to always print 'Invalid' when the validation logic is inverted.

Exam trap

Python Institute often tests the `for...else` behavior by reversing the expected logic, trapping candidates who assume `else` runs only on error or break, rather than on normal loop completion.

How to eliminate wrong answers

Option A is wrong because if the list of octets were not properly split, the script would likely raise an error or produce incorrect comparisons, not consistently print 'Invalid' for valid IPs. Option B is wrong because using 'or' instead of 'and' in the condition would cause the check to pass if any octet is within range, leading to false 'Valid' prints, not always 'Invalid'. Option C is wrong because incorrect indentation of the `else` clause would cause a syntax error or change the block association, not a consistent logical error where the `else` always runs.

58
MCQeasy

A developer is writing a simple number guessing game. The computer picks a random number between 1 and 100, and the user keeps guessing until correct. The developer implements: secret = random.randint(1,100) guess = 0 while guess != secret: guess = int(input("Guess: ")) if guess == secret: print("Correct!") else: print("Wrong, try again.") The game works, but the developer notices that if the user enters something that is not an integer, the program crashes. Which modification ensures the program handles non-integer input gracefully?

A.Use a while True loop with break
B.Change the data type of guess to string
C.Use a try-except around the input conversion
D.Add an if statement to check if input is digit
AnswerC

Wrapping the int(input(...)) conversion in try-except catches ValueError when non-numeric text is entered, letting the loop prompt again instead of crashing. This directly addresses the stem's constraint that non-integer input must be handled gracefully without terminating the guessing game.

Why this answer

Wrapping the `int(input(...))` in a `try-except` block catches the `ValueError` that occurs when the user enters a non-integer string. This allows the program to handle the error gracefully (e.g., by printing a message and continuing the loop) instead of crashing. The other options do not prevent the crash when `int()` receives invalid input.

Exam trap

Python Institute often tests the distinction between input validation (like `isdigit()`) and exception handling (`try-except`), where candidates mistakenly believe checking for digits is sufficient, ignoring that `int()` can still fail on valid-looking strings like '-5' or ' 10'.

How to eliminate wrong answers

Option A is wrong because using a `while True` loop with `break` does not handle the `ValueError` from `int()`; it only changes the loop structure, not the input conversion safety. Option B is wrong because changing `guess` to a string would prevent integer comparison with `secret`, breaking the game logic entirely. Option D is wrong because checking if the input is a digit (e.g., `input().isdigit()`) only works for positive integers and fails for negative numbers, floats, or other valid integer representations like `-5` or `+3`, and still requires a conversion that could raise an error.

59
Multi-Selecthard

Which THREE of the following are correct ways to create a list containing the numbers 1, 2, 3? (Choose three.)

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

range(1,4) yields 1, 2 and 3, stopping before the exclusive upper bound. The comprehension collects each value into a new list, producing [1, 2, 3] with the correct integers in ascending order, satisfying the question's requirement.

Why this answer

Option A, `[x for x in range(1,4)]`, is correct because a list comprehension over `range(1,4)` iterates x = 1, 2, 3 (the stop value 4 is exclusive) and builds a list `[1, 2, 3]`. Option C, `list((1, 2, 3))`, is correct because the `list()` constructor converts the tuple `(1, 2, 3)` into a new list containing those same elements. Option D, `[1, 2, 3]`, is correct because it is a direct list literal that already contains the numbers 1, 2, and 3.

Option B, `(1, 2, 3)`, does not belong because parentheses create a tuple, not a list. Option E, `{1, 2, 3}`, does not belong because curly braces create a set, which is unordered and not a list.

Exam trap

The PCEP exam often tests the distinction between list literals (`[]`), tuple literals (`()`), and set literals (`{}`), trapping candidates who confuse the syntax for these different data structures.

60
MCQhard

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

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

Positional arguments 1 and 2 are collected into the args tuple, while keyword arguments a=3 and b=4 are collected into the kwargs dictionary. Printing both objects therefore yields the tuple (1, 2) followed by the dictionary {'a': 3, 'b': 4}.

Why this answer

The function uses `*args` to capture positional arguments into a tuple and `**kwargs` to capture keyword arguments into a dictionary. When called as `func(1, 2, a=3, b=4)`, `args` becomes `(1, 2)` and `kwargs` becomes `{'a': 3, 'b': 4}`, so `print(args, kwargs)` outputs `(1, 2) {'a': 3, 'b': 4}`. Option B is correct because it matches this exact output.

Exam trap

Python Institute often tests the distinction between `*args` (tuple) and `**kwargs` (dictionary), and the trap here is that candidates mistakenly think keyword arguments are included in the tuple or that `*args` produces a list, leading them to pick options A or D.

How to eliminate wrong answers

Option A is wrong because it incorrectly combines positional and keyword arguments into a single tuple, ignoring that `**kwargs` collects keyword arguments into a dictionary, not a tuple. Option C is wrong because no TypeError occurs; the function definition correctly accepts both `*args` and `**kwargs`, and the call provides valid positional and keyword arguments. Option D is wrong because `*args` always produces a tuple, not a list; Python's `*args` packs arguments into an immutable tuple, not a mutable list.

61
MCQeasy

A Python program contains the following code: print(10 / 4) What is displayed when this program runs?

A.2
B.2.0
C.A TypeError is raised.
D.2.5
AnswerD

The division operator / always performs true division in Python 3, even when both operands are integers, and returns a float. Dividing 10 by 4 yields 2.5, so 2.5 is printed. This differs from some other languages where integer division truncates the result, but Python 3 deliberately returns the exact quotient as a float.

Why this answer

In Python 3, the single forward slash performs true division regardless of operand types, so 10 / 4 evaluates to the float 2.5. Floor division with // would instead produce 2, and integer truncation does not happen with /. The print function then displays that float value on the console.

Exam trap

The trap here is assuming Python 3 behaves like languages where dividing two integers discards the remainder, when the / operator actually returns a float.

62
MCQmedium

Evaluate the expression: not (True or False) and (False or True). What is the result?

A.SyntaxError
B.True
C.False
D.None
AnswerC

Evaluating the parentheses first: `(True or False)` yields True, and `(False or True)` yields True. Applying `not` to the first gives False, since `not True` is False. The final `and` combines False with True, producing False, satisfying the Boolean precedence rules tested here.

Why this answer

The expression is evaluated step by step: first, `True or False` evaluates to `True`; then `False or True` evaluates to `True`; the `not` operator negates the first `True` to `False`; finally, `False and True` evaluates to `False`. Therefore, the correct answer is C.

Exam trap

The trap here is that candidates often forget the precedence of `not` over `and` and `or`, or misapply short-circuit evaluation, leading them to incorrectly compute the result as `True`.

How to eliminate wrong answers

Option A is wrong because the expression uses valid Python operators and boolean values, so no SyntaxError occurs. Option B is wrong because the result is not True; the `not` operator negates the first `True` to `False`, and the `and` operator then yields `False`. Option D is wrong because the expression does not involve any function or operation that returns `None`; it produces a boolean value.

63
MCQhard

A developer wrote: x = 10; y = 5; x += y * 2. What are the values of x and y after execution?

A.x=15, y=5
B.x=30, y=5
C.x=20, y=5
D.x=20, y=10
AnswerC

Compound assignment evaluates the right-hand side first: y * 2 gives 10, then x += 10 adds it to the existing 10, yielding 20. Because the multiplication binds tighter than the augmented addition, y is never reassigned and retains its original value of 5, satisfying the stem's requirement.

Why this answer

The expression `x += y * 2` is evaluated as `x = x + (y * 2)`. Given `x = 10` and `y = 5`, `y * 2` equals 10, then `x + 10` equals 20, so `x` becomes 20. The value of `y` remains unchanged at 5 because the assignment operator `+=` only modifies `x`.

Exam trap

The PCEP exam often tests the misconception that `x += y * 2` means `(x + y) * 2`, leading candidates to pick 30, or that `y` is also modified, causing confusion with the assignment operator's scope.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes `x += y * 2` is evaluated as `(x + y) * 2`, which would give 30, but then mistakenly halves it to 15; the correct evaluation order gives 20. Option B is wrong because it assumes the multiplication applies to the entire right-hand side as `(x + y) * 2`, yielding 30, but Python's operator precedence dictates `*` binds tighter than `+=`, so only `y * 2` is multiplied. Option D is wrong because it incorrectly changes `y` to 10, but the `+=` operator only updates `x` and does not modify `y`.

64
MCQmedium

A data analyst has a list named readings containing numeric sensor values. She needs to build a new list that contains only the values strictly greater than 10, preserving their original order. Which code fragment produces this result?

A.filtered = [x for x in readings if x >= 10]
B.filtered = [x for x in readings if x > 10]
C.filtered = [x > 10 for x in readings]
D.filtered = [x for x in readings if x > 10][::-1]
AnswerB

This list comprehension iterates over readings in order, keeps each element only when x > 10, and collects the survivors into a new list. Because iteration follows the original sequence, the relative order of the kept values is preserved. It also leaves the original readings list unchanged, which matches the analyst's need to derive a filtered list rather than modify the source data.

Why this answer

A filtering list comprehension keeps only the elements that satisfy the condition and preserves their original order. Writing the element expression as x and placing the comparison after if yields the desired numeric values. Using an inclusive comparison admits boundary values, putting the comparison itself in the expression yields Booleans, and appending a reverse slice destroys the original ordering.

Exam trap

The trap here is confusing the expression position with the condition position in a comprehension, which turns a filter into a list of Boolean results.

65
Multi-Selecteasy

Which TWO of the following are valid Python variable names?

Select 2 answers
A._count
B.my_var
C.var-name
D.2nd_var
E.var name
AnswersA, B

Leading underscores are permitted as the first character of an identifier, so `_count` is a valid Python variable name. It satisfies the stem's requirement by starting with a letter or underscore rather than a digit, and containing only alphanumeric characters and underscores, with no reserved keyword conflict.

Why this answer

Option A, `_count`, is a valid Python variable name because it begins with an underscore, which is an allowed identifier character, and contains only letters and underscores. Option B, `my_var`, is also valid since it starts with a letter and uses only letters and underscores, conforming to Python's identifier rules (letters, digits, and underscores, not starting with a digit). Option C, `var-name`, is invalid because hyphens are not permitted in Python identifiers; the hyphen would be parsed as a subtraction operator.

Option D, `2nd_var`, is invalid because an identifier cannot begin with a digit. Option E, `var name`, is invalid because spaces are not allowed in identifiers.

Exam trap

Python Institute often tests the rule that hyphens and spaces are invalid in variable names, as candidates may confuse Python with other languages (like Lisp or CSS) where hyphens are allowed, or mistakenly think spaces can be used for readability.

66
MCQhard

A junior developer is working on a script that processes user data. The script reads a CSV file into a list of dictionaries. Each dictionary represents a user with keys 'name', 'age', and 'email'. The developer needs to filter out users under 18 and store their names in a list. The current code is: users = [{'name': 'Alice', 'age': 17, 'email': 'alice@example.com'}, {'name': 'Bob', 'age': 22, 'email': 'bob@example.com'}] minors = [] for user in users: if user['age'] < 18: minors.append(user['name']) print(minors) The code works, but the senior developer says it is not idiomatic and suggests a more concise solution. Which of the following approaches is the best replacement?

A.minors = [] for i in range(len(users)): if users[i]['age'] < 18: minors.append(users[i]['name'])
B.minors = [user for user in users if user['age'] < 18]
C.minors = list(map(lambda u: u['name'], filter(lambda u: u['age'] < 18, users)))
D.minors = [user['name'] for user in users if user['age'] < 18]
AnswerD

A list comprehension collapses the loop, condition, and append into one expression, producing the same filtered names list. It is the idiomatic Python replacement, satisfying the senior developer's request for conciseness while preserving identical behaviour and output.

Why this answer

It uses a list comprehension to directly extract the 'name' field from each user dictionary where the age is under 18, making the code concise and Pythonic. The original code works but is verbose; list comprehensions are the idiomatic Python approach for transforming and filtering iterables in a single readable line.

Exam trap

Python Institute often tests the distinction between filtering entire objects versus extracting specific fields, so candidates may pick Option B (which filters dictionaries) instead of Option D (which extracts the 'name' field), missing the requirement to store only names.

How to eliminate wrong answers

Option A is wrong because it uses an index-based loop with range(len(users)), which is less readable and not Pythonic; it also does not extract the 'name' field, appending the entire dictionary instead. Option B is wrong because it creates a list of entire user dictionaries (not just names), failing to meet the requirement of storing only names. Option C is wrong because it uses map() and filter() with lambda functions, which is unnecessarily complex and less readable than a list comprehension, though it would produce the correct result; it is not the best replacement for simplicity and Pythonic style.

67
MCQeasy

A Python script contains the following assignment: `value = 5` followed by `result = value * '2'`. What is the value of `result` after these statements execute?

A.A `TypeError` is raised.
B.`'22222'`
C.`'10'`
D.`10`
AnswerB

In Python, when the `*` operator has an integer and a string as operands, it performs repetition: the string is repeated that many times. With `value = 5` and the string `'2'`, the expression `value * '2'` produces the string `'22222'`, a five-character string. This is valid because string repetition is supported when one operand is an integer.

Why this answer

The multiplication operator `*` behaves differently depending on operand types. When one operand is an integer and the other is a string, Python repeats the string that many times. With `value = 5` and string `'2'`, the result is `'22222'`.

This is a common source of confusion for beginners who expect numeric multiplication or implicit type conversion. Recognizing the operand types is essential to predicting the outcome correctly.

Exam trap

The trap here is assuming that `*` always performs numeric multiplication, leading to an expectation of implicit conversion or a numeric result instead of string repetition.

68
Multi-Selecteasy

Which two of the following list methods modify the original list in place? (Choose two.)

Select 2 answers
A.sort()
B.count()
C.sorted()
D.append()
E.copy()
AnswersA, D

sort() reorders the list object itself, mutating the existing sequence rather than returning a new list. This in-place behaviour is the axis distinguishing it from non-mutating methods such as sorted(), which builds a separate list and leaves the original untouched.

Why this answer

Option A, sort(), is correct because it is a list method that reorders the list's elements directly in the existing list object and returns None, so the original list is modified in place. Option D, append(), is correct because it adds a single element to the end of the existing list object and also returns None, mutating the original list. Option B, count(), is not correct because it only returns the number of occurrences of a value and does not change the list.

Option C, sorted(), is not correct because it is a built-in function that returns a new sorted list, leaving the original list unchanged. Option E, copy(), is not correct because it returns a shallow copy of the list without modifying the original list.

Exam trap

Python Institute often tests the distinction between methods that mutate the list in place (like `sort()`) and functions that return a new list (like `sorted()`), as well as the fact that `count()` and `copy()` are non-mutating, to see if candidates confuse method behavior with function behavior.

69
MCQmedium

A Python script reads this JSON and needs to check if port 8080 is allowed. Which expression correctly checks? Assume data is already parsed into a dictionary.

A.data["ports"].contains(8080)
B.data.get("ports") == 8080
C.8080 in data["ports"]
D."ports" in data
AnswerC

Testing `8080 in data["ports"]` uses the `in` operator against the list, performing a membership check that returns `True` when the integer 8080 appears among the parsed values. This satisfies the stem's requirement to verify whether port 8080 is permitted, without iterating manually or comparing types incorrectly.

Why this answer

The `in` operator checks for membership in a list. Since `data["ports"]` is a list (e.g., `[80, 443, 8080]`), `8080 in data["ports"]` returns `True` if 8080 is present. This directly tests whether port 8080 is allowed.

Exam trap

Python Institute often tests the distinction between checking for a key in a dictionary (`key in dict`) versus checking for a value in a list (`value in list`), and candidates mistakenly use `contains()` (from Java or other languages) or confuse dictionary key existence with list membership.

How to eliminate wrong answers

Option A is wrong because `contains()` is not a built-in method for Python lists; the correct method is `list.count()` or the `in` operator. Option B is wrong because `data.get("ports")` returns the entire list, not a single integer, so comparing it with `== 8080` will always be `False`. Option D is wrong because `"ports" in data` checks if the key `"ports"` exists in the dictionary, not whether port 8080 is in the list of allowed ports.

70
Multi-Selecthard

Which THREE of the following statements about Python data types are correct? (Choose three.)

Select 3 answers
A.Strings are mutable.
B.Sets are immutable.
C.Tuples are immutable.
D.Lists are mutable.
E.Dictionaries are mutable.
AnswersC, D, E

Tuples cannot be changed after creation.

Why this answer

Tuples in Python are immutable, meaning once created, their elements cannot be changed, added, or removed. This immutability makes tuples hashable and usable as dictionary keys, unlike lists.

Exam trap

The trap here is that candidates often confuse the immutability of strings and tuples with the mutability of lists and dictionaries, or incorrectly assume sets are immutable because their elements must be immutable.

71
MCQmedium

A developer needs to iterate over the indices of a list named 'items' and print each index and its corresponding value. Which loop construct is most appropriate?

A.for val in items: print(items.index(val), val)
B.for i in range(len(items)): print(i, items[i])
C.for i, val in enumerate(items): print(i, val)
D.for i in items: print(i)
AnswerC

enumerate() yields index-value pairs directly, avoiding manual counter maintenance or range(len(items)) indexing. It satisfies the requirement to print both the index and its corresponding value in one clean iteration, which is the idiomatic and most readable construct for this task.

Why this answer

`enumerate(items)` returns an iterator that yields pairs of (index, value) directly, making it the most Pythonic and efficient way to iterate over both indices and values of a list. It avoids the overhead of calling `items.index(val)` (which is O(n) per iteration) or manually managing `range(len(items))`.

Exam trap

Python Institute often tests the distinction between iterating over values (`for val in items`) versus indices (`for i in range(len(items))`) versus both (`enumerate`), and the trap here is that candidates may choose Option B because it works, missing that `enumerate` is the idiomatic and recommended construct for this exact use case.

How to eliminate wrong answers

Option A is wrong because `items.index(val)` performs a linear search for each element, which is inefficient (O(n²) overall) and will return the first occurrence of the value, not necessarily the current index if duplicates exist. Option B is wrong because while it technically works, it is less Pythonic and more verbose than `enumerate`; it requires manual indexing and is prone to off-by-one errors if the list length changes. Option D is wrong because it iterates over the values themselves, not the indices, so it prints each value as if it were an index, which is semantically incorrect for the requirement.

72
MCQhard

A developer needs to check if a variable x is between 10 and 20 (inclusive). Which expression is correct?

A.x > 10 and x < 20
B.x < 10 and x < 20
C.10 <= x <= 20
D.x >= 10 or x <= 20
AnswerC

Python supports chained comparison operators, so 10 <= x <= 20 evaluates as (10 <= x) and (x <= 20). Both bounds are inclusive because <= is used, satisfying the stem's requirement to include 10 and 20 themselves. This is the idiomatic single expression for range checking.

Why this answer

Python supports chained comparison operators, allowing `10 <= x <= 20` to evaluate whether `x` is between 10 and 20 inclusive. This expression is equivalent to `(10 <= x) and (x <= 20)`, which checks both boundaries simultaneously.

Exam trap

The trap here is that candidates often confuse inclusive vs. exclusive boundaries and select Option A with strict inequalities, or they misunderstand that `or` (Option D) creates a condition that is always true, failing to recognize the need for `and` logic.

How to eliminate wrong answers

Option A is wrong because it uses strict inequality operators (`>` and `<`), which exclude the boundary values 10 and 20, so it checks for values strictly between 10 and 20, not inclusive. Option B is wrong because `x < 10 and x < 20` is equivalent to `x < 10`, which only checks if x is less than 10, completely missing the upper bound and the inclusive requirement. Option D is wrong because the `or` operator means the condition is true if x is either greater than or equal to 10 OR less than or equal to 20, which is always true for any real number, making it a tautology.

73
MCQmedium

A Python developer is writing a script that processes a list of sensor readings stored in the variable readings. The developer needs to iterate over the list and print each reading, but wants the loop to stop immediately if a reading of -999 is encountered, because that value indicates a sensor malfunction. Which code snippet correctly implements this behavior?

A.for reading in readings: if reading == -999: break print(reading)
B.for reading in readings: if reading != -999: print(reading) else: break
C.for reading in readings: print(reading) if reading == -999: break
D.for reading in readings: if reading == -999: continue print(reading)
AnswerA

This snippet iterates over each element in readings, checks if the current reading equals -999, and if so executes break to exit the loop immediately. The print statement is placed after the if block, so it only executes for non-malfunction readings. This matches the requirement exactly.

Why this answer

The correct implementation must iterate over the list, check for the malfunction value, and break immediately without printing that value. The snippet that places the break inside the if block and the print after the if block ensures that normal readings are printed and the loop terminates upon encountering -999. This matches the specified behavior precisely.

Exam trap

The trap here is confusing break with continue, where continue skips only the current iteration but does not stop the loop.

74
MCQeasy

A developer wrote: a, b, c = 10, 20, 30; avg = a + b + c / 3; print(avg). What is the output?

A.60.0
B.20.0
C.40.0
D.30.0
AnswerC

Operator precedence makes division bind tighter than addition, so Python evaluates c / 3 as 30 / 3 = 10.0, then adds a + b, giving 10 + 20 + 10.0 = 40.0. The float result from true division explains the decimal output.

Why this answer

Operator precedence in Python dictates that division (/) has higher precedence than addition (+). Therefore, the expression `a + b + c / 3` is evaluated as `a + b + (c / 3)`, which is `10 + 20 + (30 / 3) = 10 + 20 + 10.0 = 40.0`. The result is a float because division always returns a float in Python 3.

Exam trap

The PCEP exam often tests operator precedence by presenting an expression without parentheses, leading candidates to incorrectly assume left-to-right evaluation or to compute the average as `(a + b + c) / 3` instead of `a + b + (c / 3)`.

How to eliminate wrong answers

Option A is wrong because it assumes the entire sum is divided by 3 (i.e., `(a + b + c) / 3 = 60 / 3 = 20.0`), not 60.0. Option B is wrong because it represents the result of `(a + b + c) / 3 = 20.0`, which ignores operator precedence. Option D is wrong because it might come from incorrectly computing `c / 3 = 10.0` and then adding only `a` (10 + 10.0 = 20.0) or from a different miscalculation, but it does not match the correct evaluation.

75
MCQeasy

A student is writing a Python script to sum all even numbers in a list `nums`. The script should ignore odd numbers. Which code correctly computes the sum?

A.total = sum(nums) if nums % 2 == 0 else 0
B.total = 0 for n in nums: if n / 2 == 0: total += n
C.total = 0 for n in nums: if n % 2 == 1: total += n
D.total = 0 for n in nums: if n % 2 == 0: total += n
AnswerD

This loop checks each number for evenness using the modulo operator; if the remainder when divided by 2 is zero, the number is added to the total. Odd numbers are skipped. This correctly sums only the even numbers in the list, matching the student's requirement.

Why this answer

The correct loop uses the modulo operator to test whether each number is even, and adds only those numbers to the running total. This directly implements the requirement to sum even numbers while ignoring odd ones, using a standard accumulator pattern in Python.

Exam trap

The trap here is confusing the modulo condition for even numbers with the one for odd numbers, or mistakenly using division instead of modulo.

Page 1 of 7

Page 2

All pages