Courseiva

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

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

Page 1

Page 2 of 7

Page 3
76
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

Pythonic and direct.

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.

77
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

Chained comparison works exactly as desired.

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.

78
Multi-Selecteasy

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

Select 2 answers
A.value_2
B.value-2
C.2nd_value
D._value
E.for
AnswersA, D

Valid identifier.

Why this answer

Python variable names can contain letters, digits, and underscores, and must start with a letter or underscore. 'value_2' starts with a letter and uses an underscore, making it valid.

Exam trap

The PCEP exam often tests the rule that hyphens are illegal in variable names, as candidates may confuse them with underscores or assume they are allowed like in some other languages.

79
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

Correct: 10 + 20 + (30/3) = 40.

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.

80
MCQhard

Which of the following is the most efficient (Pythonic) way to create a list of squares for numbers 0 through 9?

A.squares = [i*i for i in range(10)]
B.squares = []; for i in range(10): squares.append(i*i)
C.squares = list(map(lambda x: x*x, range(10)))
D.squares = (i*i for i in range(10))
AnswerA

List comprehension is preferred.

Why this answer

Uses a list comprehension, which is the most Pythonic and efficient way to create a list because it combines iteration and list construction in a single, readable expression. It avoids the overhead of repeated method calls (like `append`) and is faster than `map` with a lambda due to reduced function call overhead.

Exam trap

The PCEP exam often tests the distinction between list comprehensions and generator expressions, trapping candidates who confuse the lazy evaluation of generators with the eager construction of lists.

How to eliminate wrong answers

Option B is wrong because it uses an explicit loop with `append`, which is less efficient and less Pythonic than a list comprehension, though it produces the same result. Option C is wrong because `map` with a lambda is less efficient and less readable than a list comprehension; the lambda adds function call overhead for each element, and `map` returns an iterator in Python 3, requiring an explicit `list()` call to get a list. Option D is wrong because it creates a generator expression (not a list), which yields values lazily and cannot be indexed or sliced like a list; it does not produce a list of squares.

81
Multi-Selectmedium

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

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

Immutable.

Why this answer

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

Exam trap

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

82
MCQhard

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

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

Correctly sets bit 1 and clears bit 3

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

83
Multi-Selectmedium

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

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

Correct: Python supports both positional and keyword arguments.

Why this answer

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

Exam trap

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

84
MCQmedium

What is the output of the code?

A.No output
B.0 1 2 3 4
C.0 1 2 4
D.0 1 2 4 5
AnswerC

Correct: 3 is skipped.

Why this answer

The code uses a for loop with range(5) to iterate over numbers 0 through 4. Inside the loop, an if statement checks if the current number equals 3; if true, the continue statement skips the remainder of the current iteration and moves to the next iteration. Therefore, when i is 3, the print(i) statement is skipped, but the loop continues with i=4, printing 4.

Thus, the output is '0 1 2 4' (each on a new line). Option C correctly lists the printed values as 0, 1, 2, and 4.

Exam trap

Python Institute often tests the interaction between break and loop iteration order, where candidates mistakenly think break skips only the current iteration (like continue) or that the loop continues after the break condition is met.

How to eliminate wrong answers

Option A is wrong because the loop does produce output: it prints 0, 1, and 2 before the break occurs. Option B is wrong because it includes 3 and 4, but the break at i == 3 prevents printing 3 and any subsequent numbers. Option D is wrong because it includes 5, but the range(5) generates numbers 0-4, so 5 is never reached, and the break also stops before 4 is printed.

85
MCQmedium

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

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

Equality comparison.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

86
MCQeasy

Consider the following code: x = input('Enter a number: ') print(x + x) A user enters 5 at the prompt. What is printed?

A.55
B.10
C.5
D.25
AnswerA

String '5' repeated twice.

Why this answer

55 because Python's input() function returns a string. When the user enters 5, it is stored as the string '5'. If the code then uses the + operator to concatenate this string with itself (e.g., print(input() + input()) or print(x + x)), the result is '55', not numeric addition.

Exam trap

The PCEP exam often tests the distinction between string concatenation and numeric addition, exploiting the fact that `input()` returns a string, so candidates mistakenly assume automatic type conversion to integer.

How to eliminate wrong answers

Option B is wrong because it assumes the input is converted to an integer and added (5+5=10), but no `int()` conversion is performed. Option C is wrong because it suggests only one '5' is printed, ignoring the concatenation of the two strings. Option D is wrong because it implies multiplication (5*5=25), which would require the `*` operator and numeric conversion.

87
MCQeasy

Which operator performs integer (floor) division in Python?

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

Correct operator for integer division.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

88
MCQeasy

What is the output of the code?

A.1 2
B.1 2 3 Done
C.1 2 Done
D.1 2 3
AnswerA

Correct: prints 1, then 2, then loop ends.

Why this answer

The code uses a `for` loop with `range(1, 4)` which generates the sequence 1, 2, 3. Inside the loop, `if i == 3: break` causes the loop to terminate when `i` equals 3, so the loop only prints 1 and 2 before breaking. There is no additional print statement after the loop, so the output is just `1` and `2` on separate lines.

Exam trap

Python Institute often tests the distinction between `break` and `continue`, and the trap here is that candidates forget that `break` exits the loop entirely, not just the current iteration, leading them to incorrectly include the value that triggered the break in the output.

How to eliminate wrong answers

Option A is wrong because it omits 'Done' and shows only 1 and 2, but the code prints 'Done' after the loop. Option B is wrong because it prints 3 before 'Done', but the `break` statement prevents 3 from being printed. Option D is wrong because it prints 1, 2, 3 without 'Done', but the code includes `print('Done')` after the loop.

89
MCQhard

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

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

except Exception: catches all exceptions that inherit from Exception, excluding KeyboardInterrupt and SystemExit.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

90
MCQmedium

Refer to the exhibit. What is the output?

A.5
B.2
C.9
D.1
AnswerD

After bubble sort, the smallest element is at index 0.

Why this answer

(1). The code initializes x to 0, then iterates over the list [1, 2, 3, 4, 5]. In each iteration, it first assigns the current number to x, then checks if the number equals 1.

On the first iteration, i is 1, so x becomes 1, then the condition i == 1 is true, causing the loop to break. The print(x) statement after the loop outputs the final value of x, which is 1.

Exam trap

Candidates might mistakenly think that the break occurs before the assignment of x, so x remains 0. However, the code assigns x = i before checking the condition, so x becomes 1 before the loop breaks.

How to eliminate wrong answers

Option A (5) is wrong because it assumes the loop completes all iterations without breaking, but the break statement exits the loop when the condition is met, so the last value of 'x' is not 5. Option B (2) is wrong because it assumes the loop processes up to the element before the break, but the break occurs at the first element (1) if the condition is 'x == 1', so 'x' is never updated to 2. Option C (9) is wrong because it is not a value present in the list or derived from the loop logic; it likely results from a misunderstanding of the loop range or break behavior.

91
MCQeasy

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

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

True division returns 2.5.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

92
MCQhard

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

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

This targets only the expected exceptions, letting others propagate as intended.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

93
MCQhard

A developer is implementing a toggle switch feature. The variable flag starts as False. Which code snippet correctly toggles the flag and performs an action based on the new value each time the code is run? (Assume action1 is performed when flag is True, action2 when False.)

A.flag = not flag; if flag: action1() else: action2()
B.if not flag: flag = True; action1() else: flag = False; action2()
C.if flag: flag = False; action1() else: flag = True; action2()
D.flag = not flag; if flag: action2() else: action1()
AnswerA

Correctly toggles then uses new value.

Why this answer

It first toggles the flag using `flag = not flag`, which flips the boolean value from False to True (or vice versa). Then it uses a conditional `if flag:` to check the new value and calls `action1()` when True or `action2()` when False, exactly matching the requirement to act on the new state each time the code runs.

Exam trap

Python Institute often tests the order of operations in toggle-and-check patterns, where candidates mistakenly perform the action based on the old flag value instead of the new one after toggling.

How to eliminate wrong answers

Option B is wrong because it checks `if not flag:` first, then sets `flag = True` and calls `action1()` — but when `flag` is False, it toggles to True and runs `action1()` (correct for True), but the `else` branch sets `flag = False` and calls `action2()` — this logic is inverted: it runs `action1()` when the new flag is True but the structure is confusing and the else branch incorrectly sets flag to False when it was already True, failing to toggle properly. Option C is wrong because it checks `if flag:` first, then sets `flag = False` and calls `action1()` — this runs `action1()` when the new flag is False (since it just set it to False), which is the opposite of the requirement (action1 should run when flag is True). Option D is wrong because it correctly toggles the flag with `flag = not flag`, but then checks `if flag:` and calls `action2()` instead of `action1()`, swapping the actions — so when flag becomes True, it incorrectly runs `action2()`.

94
MCQhard

A team observes that the following code prints 'Found' even when the item is not in the list. Code: for item in mylist: if item == target: print('Found'); break; else: print('Not found'). Which modification ensures it correctly prints 'Not found' only if the item is not present?

A.Move else inside the if block
B.Replace break with continue
C.Use a flag variable to track found status
D.Align the else with the for statement (for-else construct)
AnswerD

Correct: for-else executes else only if no break occurred.

Why this answer

The original code uses a for-else construct where the else block executes after the loop completes normally (i.e., without a break). However, the code has a syntax error: the else is incorrectly indented as part of the if statement, causing it to execute on every iteration when the condition is false. Aligning the else with the for statement (for-else construct) ensures the else block runs only if the loop finishes without hitting a break, which occurs when the item is not found.

Exam trap

Python Institute often tests the for-else construct by presenting code where the else is incorrectly indented under the if, leading candidates to think the else belongs to the if statement, when in fact the intended behavior requires the else to be aligned with the for.

How to eliminate wrong answers

Option A is wrong because moving the else inside the if block would cause it to execute only when item == target is true, printing 'Not found' incorrectly when the item is found, and never printing it when the item is not present. Option B is wrong because replacing break with continue would prevent the loop from exiting upon finding the item, causing the else block (if properly aligned) to never execute and the loop to continue iterating, potentially printing 'Found' multiple times and never printing 'Not found'. Option C is wrong because while using a flag variable could work, it is not the modification described in the question; the question asks which modification ensures correct behavior, and the for-else construct is the direct, Pythonic fix that avoids unnecessary extra variables.

95
MCQmedium

A system administrator is writing a Python script to monitor disk usage. The script uses the psutil library (not part of PCEP scope, but the scenario is generic). The administrator writes: import psutil disk = psutil.disk_usage('/') print(disk.free) But the script fails with an ImportError because psutil is not installed. The administrator decides to handle this gracefully: if the module is missing, the script should print a custom error message and exit without crashing. Which code snippet achieves this?

A.try: import psutil except ImportError: print('psutil not installed. Please install.') sys.exit(1)
B.import psutil if not psutil: print('psutil not installed.') sys.exit(1)
C.try: import psutil except ImportError: print('psutil not installed. Please install.')
D.try: import psutil except: print('Module missing.') raise
AnswerA

Catches ImportError and exits gracefully.

Why this answer

It uses a try-except block to catch the ImportError specifically when the import statement fails. This allows the script to print a custom error message and then call sys.exit(1) to terminate gracefully with a non-zero exit code, which is the standard way to signal failure in a script. The other options either do not handle the missing module correctly or fail to exit the script properly.

Exam trap

Python Institute often tests the distinction between handling an exception with a graceful exit versus merely printing a message and continuing, or re-raising the exception, which still causes a crash; candidates may overlook the need for sys.exit(1) or mistakenly think a bare except or a falsy check on the module name is sufficient.

How to eliminate wrong answers

Option B is wrong because it attempts to check if the module is falsy after import, but if the import fails, the script will crash with an ImportError before reaching the if statement; Python does not assign a falsy value to a failed import. Option C is wrong because it catches the ImportError and prints a message but does not call sys.exit(1), so the script would continue executing after the except block, potentially causing further errors or undefined behavior. Option D is wrong because it uses a bare except clause (which is too broad and can mask unrelated errors) and then calls raise, which re-raises the caught exception, causing the script to crash with a traceback instead of exiting gracefully with a custom message.

96
MCQeasy

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

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

Correct; robustly handles all non-integer inputs.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

97
MCQhard

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

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

Correct: remainder 0 means divisible.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

98
MCQmedium

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

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

Correct; startswith checks prefix.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

99
MCQhard

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

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

0.1+0.2 equals 0.30000000000000004, not exactly 0.3.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

100
MCQhard

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

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

The else clause executes when the loop finishes normally (no break). Here, it appends the row if no even item was found.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

101
Multi-Selectmedium

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

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

Correct: break terminates the innermost loop immediately.

Why this answer

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

Exam trap

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

102
Multi-Selecthard

A Python script contains the following code: x = [1, 2, 3] y = x y.append(4) z = x.copy() z.append(5) After execution, which TWO of the following statements are true? (Choose two.)

Select 2 answers
A.x and y refer to different list objects
B.x is equal to [1, 2, 3]
C.x is equal to [1, 2, 3, 4]
D.x is equal to [1, 2, 3, 4, 5]
E.z is equal to [1, 2, 3, 5]
AnswersC, E

y is a reference to x; appending to y modifies x.

Why this answer

`y = x` creates a reference to the same list object, not a copy. When `y.append(4)` is called, it modifies the shared list, so `x` becomes `[1, 2, 3, 4]`. This demonstrates that assignment in Python does not copy objects; it binds a new name to the existing object.

Exam trap

The PCEP exam often tests the distinction between reference assignment and copying; the trap here is that candidates mistakenly think `y = x` creates a new list, leading them to believe `x` remains unchanged after `y.append(4)`.

103
MCQhard

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

A.[10, 20, 60, 80, 100]
B.[15, 20, 30, 40, 50]
C.[15, 25, 60, 80, 100]
D.[15, 20, 60, 80, 100]
AnswerD

Correct as the code produces [15, 20, 60, 80, 100].

Why this answer

The code iterates over the list [10, 20, 30, 40, 50]. For elements greater than 20, it appends the element multiplied by 2. For element 10 (which is less than 20), it increases by 5 and appends 15.

For element 20 (equal to 20, not greater), it appends the original value 20. This results in [15, 20, 60, 80, 100], matching option D.

Exam trap

The PCEP exam often tests the distinction between `>` and `>=` — candidates mistakenly treat `20 > 20` as `True` and multiply 20, or forget that the `else` branch (implicitly) appends the original value unchanged.

How to eliminate wrong answers

Option A is wrong because it incorrectly includes 10 and 20 unchanged but then shows 60, 80, 100 — this would be correct only if the condition were `if x >= 20`, but the code uses `> 20`. Option B is wrong because it shows `[15, 20, 30, 40, 50]`, which would result from adding 5 to each element, not from the conditional multiplication logic. Option C is wrong because it shows `[15, 25, 60, 80, 100]`, which would result from adding 5 to the first two elements and multiplying the rest by 2, but the code appends the original value (not modified) for elements not greater than 20.

104
Multi-Selecthard

Which TWO of the following code snippets will produce the output 'True'? (Assume all variables are defined appropriately.)

Select 2 answers
A.x=2.0; y=2.0; print(x is y)
B.print(1 < 2 < 1)
C.print('ab' == 'ba')
D.print(3.0 == int(3.0))
E.a=256; b=256; print(a is b)
AnswersD, E

Value comparison coerces types, both equal 3.

Why this answer

`int(3.0)` converts the float 3.0 to the integer 3, and the `==` operator compares values, not types. Since 3.0 and 3 represent the same numeric value, the comparison returns True. This demonstrates that `==` performs value equality, not identity.

Exam trap

The PCEP exam often tests the difference between `is` (identity) and `==` (equality), and the trap here is that candidates assume `is` compares values like `==` does, or they forget that integer interning is an implementation detail not guaranteed for all values.

105
MCQhard

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

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

Deep copy recursively copies all objects, making the new dictionary completely independent.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

106
MCQmedium

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

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

Why this answer

The code iterates over the list `[[1,2],[3,4],[5,6]]` and for each inner list, it sets the element at index 1 to 0. This mutates each inner list in place, producing `[[1,0],[3,0],[5,0]]`. The original list is then printed, showing the modified nested list.

Exam trap

The PCEP exam often tests the distinction between modifying list elements in place versus creating new lists, and the trap here is that candidates mistakenly think the loop creates new sublists or that only the outer list is modified, leading them to choose the original or incorrectly altered output.

How to eliminate wrong answers

Option B is wrong because it represents the original unmodified list, but the code explicitly changes the second element of each sublist to 0. Option C is wrong because it shows all elements as 0, which would only happen if both indices in each sublist were set to 0, but only index 1 is changed. Option D is wrong because it sets the first element of each sublist to 0 and keeps the second element unchanged, which is the opposite of what the code does (it sets index 1 to 0, not index 0).

107
MCQmedium

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

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

Cannot concatenate str and int.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

108
MCQhard

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

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

Correct: without base case, recursion never terminates, exceeding max recursion depth.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

109
MCQhard

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

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

Correct; the ValueError is raised and caught.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

110
MCQhard

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

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

Mutating the input data violates the principle of avoiding side effects.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

111
Multi-Selecthard

A developer is debugging a function that uses a while loop to reverse a list in place. The current code causes an infinite loop. Which three modifications would likely fix the infinite loop? (Select three.)

Select 3 answers
A.Ensure the end index is decremented each iteration
B.Add a break statement after the swap
C.Use a temporary variable for the swap
D.Ensure the start index is incremented each iteration
E.Use a for loop instead
AnswersA, D, E

Necessary to eventually meet start condition.

Why this answer

In a while loop that reverses a list in place, the end index must be decremented each iteration to move the end pointer toward the center. Without decrementing the end index, the loop condition (e.g., start < end) may never become false, causing an infinite loop. This ensures the two pointers converge and the loop terminates.

Exam trap

Python Institute often tests the misconception that adding a break or using a temporary variable alone can fix an infinite loop, when the root cause is missing index updates that prevent the loop condition from becoming false.

112
MCQhard

Which of the following will raise a TypeError?

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

Tuples are immutable; assignment to element raises TypeError.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

113
MCQhard

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

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

Correct: floor division rounds toward negative infinity.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

114
MCQhard

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

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

Lists are unhashable and cannot be used as dictionary keys.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

115
MCQmedium

A developer needs to write a loop that prints all even numbers from a list. They attempt: for num in numbers: if num % 2 == 0: print(num). However, they want a more efficient approach using list comprehension. Which alternative achieves the same result?

A.print([num for num in numbers if num % 2 == 0])
B.for num in numbers: print(num if num % 2 == 0 else None)
C.for even in [num for num in numbers if num % 2 == 0]: print(even)
D.print([num % 2 == 0 for num in numbers])
AnswerC

Correct: list comprehension filters even numbers, then loop prints each.

Why this answer

It uses a list comprehension to generate a list of even numbers, then iterates over that list with a for loop, printing each even number. This achieves the same result as the original loop but with the efficiency of list comprehension for filtering, while still printing each number individually.

Exam trap

Python Institute often tests the distinction between generating a list of filtered values versus printing them individually, and the trap here is that candidates may think option A is correct because it uses list comprehension, but they overlook that it prints the entire list as a single output, not each element separately.

How to eliminate wrong answers

Option A is wrong because it prints the entire list of even numbers as a single list object, not each number individually. Option B is wrong because it prints None for every odd number (due to the else clause), altering the output. Option D is wrong because it prints a list of boolean values (True/False) indicating whether each number is even, not the even numbers themselves.

116
Multi-Selecteasy

Which TWO of the following are valid Python data types?

Select 2 answers
A.int
B.string
C.char
D.float
E.double
AnswersA, D

int is a built-in type.

Why this answer

`int` is a built-in numeric data type in Python used to represent whole numbers without a fractional component. Python's `int` type has arbitrary precision, meaning it can handle arbitrarily large integers limited only by available memory.

Exam trap

Python Institute often tests the distinction between Python's actual type names (`int`, `float`, `str`) and type names from other languages (like `string`, `char`, `double`), expecting candidates to know that Python uses `str` for strings and `float` for double-precision numbers, and has no separate `char` or `double` types.

117
MCQmedium

A programmer is writing a script to read a number, determine if it is even or odd, and then also use the number to calculate its square. The code: num = input("Enter a number: ") if num % 2 == 0: print("Even") else: print("Odd") square = num ** 2 print("Square:", square) When run, a TypeError occurs on the modulo line. Which fix will resolve the error and allow the later calculation to work?

A.Change the condition to: if num // 2 == 0:
B.Change the condition to: if float(num) % 2 == 0:
C.Change the condition to: if int(num) % 2 == 0:
D.Change the input to: num = int(input("Enter a number: "))
AnswerD

This converts to int at the source, so all operations work.

Why this answer

The `input()` function always returns a string, and the modulo operator `%` and exponentiation operator `**` require numeric operands. By converting the input to an integer with `int(input(...))`, both the modulo and exponentiation operations work correctly, resolving the TypeError and allowing the square calculation to proceed.

Exam trap

Python Institute often tests the misconception that converting the input type only on the line where the error occurs is sufficient, but the trap is that the variable remains a string for subsequent operations, so a single conversion at assignment is the correct fix.

How to eliminate wrong answers

Option A is wrong because `//` is floor division, not modulo; `num // 2 == 0` would check if the integer division result is zero, which is not equivalent to checking evenness and still requires `num` to be numeric. Option B is wrong because `float(num) % 2 == 0` converts the input to a float, but floating-point modulo with 2 can produce imprecise results (e.g., 4.0 % 2.0 == 0.0, but 4.2 % 2.0 == 0.1999999999999993), and the later `**` operation would still fail if `num` remains a string. Option C is wrong because while `int(num) % 2 == 0` fixes the modulo line, it does not change the original `num` variable; the later `square = num ** 2` still uses the string `num`, causing a TypeError on that line.

118
MCQhard

A system administrator wrote a Python script to monitor disk usage. The script reads the output of a system command that returns a string like 'Used: 45%' and extracts the percentage. The code uses slicing to get the numeric part and converts to int. However, on some servers, the output format changes to 'Used: 45.2%', causing a ValueError when converting to int. The administrator needs a robust solution that works with both integer and floating-point percentages while still producing an integer result (e.g., 45 for 45.2%). Which option is the best approach?

A.Use string splitting to extract the numeric part, then convert to float and round to the nearest integer.
B.Use a regular expression to extract the number and convert to float, then convert to int.
C.Use the .replace() method to remove the '%' character and then convert to int.
D.Use a try-except block to attempt int conversion first; if a ValueError occurs, convert to float and then convert to int (which truncates the decimal part).
AnswerD

This handles both integer and floating-point inputs by attempting direct int conversion first, and falling back to float then int truncation.

Why this answer

It uses a try-except block to first attempt int conversion for integer percentages, and if a ValueError occurs (due to a decimal point), it converts to float and then to int, which truncates the decimal part. This approach handles both '45%' and '45.2%' formats without raising an error, producing an integer result as required.

Exam trap

Python Institute often tests the distinction between int() and float() conversion behavior, and the trap here is that candidates may overlook that int('45.2') raises a ValueError, leading them to choose a simpler but incorrect approach like direct int conversion after removing '%'.

How to eliminate wrong answers

Option A is wrong because using string splitting to extract the numeric part and then rounding with round() would produce a float (e.g., 45.2 rounds to 45.0) or require additional conversion, and it does not handle the case where the numeric part is already an integer without a decimal point. Option B is wrong because converting to float and then to int truncates the decimal part (e.g., 45.2 becomes 45), but using a regular expression is unnecessarily complex and less readable for this simple task; also, it does not provide a fallback for integer-only strings. Option C is wrong because using .replace() to remove '%' and then converting to int will fail with a ValueError if the string contains a decimal point (e.g., '45.2' cannot be directly converted to int).

119
Multi-Selecthard

Which THREE of the following expressions evaluate to True?

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

Equal.

Why this answer

The equality operator '==' compares the integer values 3 and 3, which are identical, so the expression evaluates to True. In Python, '==' checks for value equality, not identity, and since both operands are the same integer literal, the result is True.

Exam trap

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

120
MCQeasy

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

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

Correct; assignment to tuple element raises TypeError.

Why this answer

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

121
MCQhard

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

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

print('Hello', name) prints 'Hello' then a space then the value of name.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

122
Multi-Selecthard

Which THREE of the following are valid Python variable names?

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

Letters and digits allowed.

Why this answer

Python variable names must start with a letter or underscore, and can contain letters, digits, and underscores. 'myVar2' begins with a letter and uses only valid characters, making it a legal identifier.

Exam trap

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

123
MCQeasy

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

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

Correct squares of even numbers.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

124
Multi-Selectmedium

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

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

Built-in boolean type.

Why this answer

`bool` is a built-in data type in Python, used to represent Boolean values `True` and `False`. It is a subclass of `int` and is fundamental for logical operations and conditional expressions.

Exam trap

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

125
MCQeasy

What is the output of the code?

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

The get() method returns the default value 'Key not found' when the key is absent, so this is printed.

Why this answer

The code uses a dictionary's `get()` method with a default value of 'Key not found'. When the key 'b' is not present in the dictionary `d`, `get()` returns the specified default instead of raising an exception. Therefore, the output is 'Key not found', making option D correct.

Exam trap

The PCEP exam often tests the distinction between `dict[key]` (which raises `KeyError`) and `dict.get(key, default)` (which returns the default), trapping candidates who expect an exception or assume the default is `None`.

How to eliminate wrong answers

Option A is wrong because `get()` does not raise an `AttributeError`; it is a built-in dictionary method that safely handles missing keys. Option B is wrong because the program does not exit silently; `print()` always outputs something, and in this case it outputs the default value. Option C is wrong because `None` would only be returned if no default argument were provided to `get()`; here the explicit default 'Key not found' overrides that behavior.

126
MCQhard

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

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

Correct. The expression evaluates to 10.

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

127
MCQmedium

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

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

String comparison can yield unexpected results; convert to int.

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

128
MCQeasy

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

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

Correct; print is skipped for 3.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

129
MCQmedium

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

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

Correct. This uses tuple unpacking to swap values.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

130
Multi-Selectmedium

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

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

Underscore is allowed at start.

Why this answer

(_count) is correct because in Python, variable names can start with an underscore, and underscores are allowed anywhere in the name. Option E (myVar) is correct because it starts with a letter and contains only letters and digits, which is valid. Both follow Python's identifier rules: must start with a letter or underscore, followed by letters, digits, or underscores.

Exam trap

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

131
MCQhard

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

A.4
B.Loop ended normally\n4
C.7
D.1
AnswerA

Why this answer

The code iterates over the list `[1, 2, 3, 4]` and breaks out of the loop when `i == 3`, so only the first three iterations execute. The `else` clause on the `for` loop runs only if the loop completes without a `break`, so it is skipped. The final value of `i` after the loop is 3, but the code prints `i + 1`, which yields 4.

Exam trap

The trap here is that candidates often forget that the `else` clause of a loop is skipped when a `break` occurs, and they mistakenly think the loop variable resets or that the `else` always runs.

How to eliminate wrong answers

Option B is wrong because the `else` clause does not execute when a `break` occurs, so 'Loop ended normally' is never printed. Option C is wrong because it assumes the loop prints the value of `i` when `i == 3` (which would be 3), but the code prints `i + 1` after the loop, not during the iteration. Option D is wrong because it suggests the loop stops at the first element, but the break condition is `i == 3`, not `i == 1`.

132
MCQhard

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

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

Handles all non-numeric lines, warns about skipped lines.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

133
MCQhard

The above JSON is loaded into a Python dictionary named data using json.load(). A developer writes: print(data['languages'][1][:3]) What is printed?

A.IndexError
B.Jav
C.Java
D.Pyt
AnswerB

Index 1 'Java', first 3 chars.

Why this answer

The JSON data is loaded into a Python dictionary. The key 'languages' maps to a list of strings. Indexing with [1] retrieves the second element, which is 'Java'.

Then slicing with [:3] extracts the first three characters, resulting in 'Jav'. Therefore, option B is correct.

Exam trap

The PCEP exam often tests the combination of list indexing and string slicing, where candidates may forget that slicing returns a substring of the specified length, not the full string, or may misidentify the zero-based index of the list element.

How to eliminate wrong answers

Option A is wrong because IndexError would only occur if the index or slice is out of range, but here the list has at least two elements and the string 'Java' has more than three characters, so no error is raised. Option C is wrong because it assumes the slice [:3] returns the full string 'Java', but slicing with [:3] returns only the first three characters, not the entire string. Option D is wrong because it confuses the index: [1] accesses the second element 'Java', not the first element 'Python', and slicing [:3] on 'Python' would give 'Pyt', but that is not what the code does.

134
Multi-Selecthard

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

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

Sorts the list in place.

Why this answer

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

Exam trap

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

135
MCQeasy

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

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

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

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

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

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

136
MCQmedium

What is the output of the code?

A.['Positive', 'Zero']
B.[Positive, Zero, Negative]
C.('Positive', 'Zero', 'Negative')
D.['Positive', 'Zero', 'Negative']
AnswerD

Correct: as explained.

Why this answer

The question stem does not contain any code. Without the code, it is impossible to determine the output. The explanation previously assumed a specific code snippet which is not present.

Exam trap

Python Institute often tests the distinction between list literals (square brackets) and tuple literals (parentheses), and the requirement for string literals to be quoted — candidates may forget quotes or confuse list/tuple syntax.

How to eliminate wrong answers

Option A is wrong because it suggests only 'Positive' and 'Zero' are in the list, but the code (as implied by the correct answer) includes 'Negative' as well. Option B is wrong because it uses bare words without quotes, which would cause a NameError in Python (undefined variables), not a list of strings. Option C is wrong because it shows a tuple with parentheses, but the code uses square brackets for a list, so the output is a list, not a tuple.

137
MCQmedium

A developer encounters a TypeError. Which line of code likely caused it?

A.value = eval(input("Enter a number: "))
B.value = float(input("Enter a number: "))
C.value = int(input("Enter a number: "))
D.value = input("Enter a number: ")
AnswerD

input() returns a string, causing the TypeError.

Why this answer

The error in question is a TypeError that occurs when a string is used in an arithmetic operation (e.g., adding a string to an integer). Option D returns a string, so subsequent code expecting a number will fail. Options A, B, and C all return numeric types, so they would not cause that specific error.

Exam trap

Candidates often assume the error is a ValueError from failed conversion, but the actual error that occurs with option D is a TypeError from using the unconverted string in arithmetic.

How to eliminate wrong answers

Option A is wrong because `eval(input(...))` can raise a `ValueError` if the input is not a valid Python expression, but more commonly it raises a `NameError` or `SyntaxError`; however, the question's error is specifically a `ValueError`, which is not typical for `eval()` on a non-numeric string. Option B is wrong because `float(input(...))` will raise a `ValueError` if the input string cannot be converted to a float (e.g., 'abc'), but the error shown could be from this; however, the question asks which line likely caused it, and D is the only one that does not cause a `ValueError`. Option C is wrong because `int(input(...))` will raise a `ValueError` if the input is not a valid integer literal (e.g., '12.5' or 'abc'), which is a common source of `ValueError` in PCEP questions.

138
MCQeasy

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

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

10 // 3 = 3, 10 % 3 = 1.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

139
MCQeasy

Refer to the exhibit. What is the output?

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

Correct. Only elements at odd indices are modified as described, yielding [1,4,3,8,5].

Why this answer

The code iterates over the list `[1, 2, 3, 4, 5]` using indices. It only modifies elements at odd indices (index 1 and 3). For those elements, if the value is even, it multiplies by 2; if odd, it adds 2.

At index 1, value 2 (even) becomes 4; at index 3, value 4 (even) becomes 8. Elements at even indices (0, 2, 4) remain unchanged: 1, 3, 5. Thus the final list is `[1, 4, 3, 8, 5]`.

Exam trap

Candidates often mistakenly apply the operation to every element instead of only odd indices, or they confuse the operation (multiply vs add) based on the element's parity, leading them to choose option B ([2,4,6,8,10]) or D ([1,2,3,4,5]).

How to eliminate wrong answers

Option A is wrong because it suggests the output is `[2, 5, 7, 9, 5]`, which would require a mix of operations not present in the code (e.g., adding 3 to some elements). Option B is wrong because it assumes the code creates a new list with all elements transformed, but the actual code modifies the original list in-place and the condition checks for even numbers (not odd). Option D is wrong because it implies no transformation occurs, but the code explicitly changes each element based on the condition.

140
MCQmedium

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

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

10 * 20 = 200, plus 5 = 205.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

141
MCQeasy

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

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

Correct: y remains 5.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

142
Multi-Selecthard

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

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

Prints 0..4.

Why this answer

`range(0,5)` generates the sequence 0, 1, 2, 3, 4. The `range()` function with two arguments (start, stop) produces numbers from start inclusive up to, but not including, stop. Therefore, iterating with `for i in range(0,5): print(i)` prints exactly 0 through 4.

Exam trap

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

143
MCQhard

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

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

Correct. a still references 'abc'.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

144
MCQeasy

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

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

Correct; int and str cannot be combined with +.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

145
MCQhard

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

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

Correct evaluation as described

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

146
Multi-Selecthard

Which TWO of the following expressions will evaluate to True?

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

True, numeric comparison.

Why this answer

In Python, the '==' operator compares values, and since integers and floats are compared by numeric value, 3 and 3.0 are numerically equal, so the expression evaluates to True. Option E is correct because 'is' checks object identity, and small integers like 3 are interned by Python, meaning they refer to the same object in memory, so '3 is 3' returns True.

Exam trap

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

147
MCQeasy

A developer writes a script that prompts the user for their age and stores it in a variable. Which code snippet correctly converts the input to an integer?

A.age = int(input)
B.age = int(input("Enter age: "))
C.age = input("Enter age: ", int)
D.age = input(int("Enter age: "))
AnswerB

Correctly converts the input string to an integer.

Why this answer

It uses the `int()` function to convert the string returned by `input()` into an integer. The `input()` function always returns a string, so wrapping it with `int()` performs the type conversion needed for numeric operations.

Exam trap

Python Institute often tests the distinction between a function reference (e.g., `input` without parentheses) and a function call (e.g., `input()`), leading candidates to mistakenly think `int(input)` is valid syntax.

How to eliminate wrong answers

Option A is wrong because `input` without parentheses is a reference to the function object, not a function call, so it does not prompt the user or return a value. Option C is wrong because `input()` does not accept a second argument; the prompt is the only parameter, and passing `int` as a second argument causes a TypeError. Option D is wrong because it attempts to call `int()` on a string before calling `input()`, which would raise a NameError since `"Enter age: "` is not a defined variable, and the parentheses are misplaced.

148
MCQeasy

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

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

Returning allows the result to be used in other calculations.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

149
MCQmedium

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

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

not (a > b) = not (5 > 10) = not False = True

Why this answer

Only option C evaluates to True. Option C: not (5 > 10) = not False = True. Option D: a == b or False = 5 == 10 or False = False or False = False.

Options A and B are also False.

Page 1

Page 2 of 7

Page 3

All pages