Courseiva

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

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

Page 1 of 7

Page 2
1
Multi-Selecteasy

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

Select 2 answers
A.my-var
B._myVar
C.2ndValue
D.class
E.my_var
AnswersB, E

Underscore at start is allowed.

Why this answer

In Python, variable names can start with an underscore, and `_myVar` follows the naming rules: it begins with a letter or underscore, contains only letters, digits, or underscores, and is not a reserved keyword. Underscore-prefixed names are commonly used for internal or private variables by convention.

Exam trap

The PCEP exam often tests the rule that hyphens are invalid in variable names (tricking candidates who confuse them with underscores) and that keywords like `class` are reserved, even though they look like valid identifiers.

2
MCQhard

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

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

Catches all invalid literals, logs line number, and continues.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

3
MCQhard

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

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

Correct; type returns <class 'float'>, which equals float.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

4
MCQeasy

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

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

Correct output.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

5
Multi-Selecthard

Which two of the following expressions return the value 5? (Choose two.)

Select 2 answers
A.10 % 5
B.10 // 2
C.10 ** 0
D.10 / 2
E.5 * 1
AnswersB, E

Floor division yields 5

Why this answer

(10 // 2) uses floor division, which divides 10 by 2 and returns the integer quotient 5. This is correct because floor division in Python discards any fractional remainder, yielding an exact integer result.

Exam trap

Python Institute often tests the difference between / (float division) and // (integer floor division), trapping candidates who assume / returns an integer when the division is exact.

6
Multi-Selectmedium

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

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

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

Why this answer

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

Exam trap

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

7
MCQhard

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

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

Correct and idiomatic.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

8
MCQeasy

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

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

Correct: follows precedence and left-associativity.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

9
Multi-Selecteasy

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

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

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

Why this answer

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

Exam trap

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

10
MCQeasy

Which of the following is a valid Python variable name?

A.2var
B.var name
C.var-name
D._var
AnswerD

Underscore is allowed as first character.

Why this answer

(_var) is correct because in Python, variable names must start with a letter or an underscore, and can contain letters, digits, and underscores. The underscore is explicitly allowed as the first character, making _var a valid identifier.

Exam trap

Python Institute often tests the misconception that hyphens or spaces are acceptable in variable names because they appear in other programming languages or file naming conventions, but Python strictly prohibits them.

How to eliminate wrong answers

Option A is wrong because variable names cannot start with a digit; '2var' begins with '2', which violates Python's identifier rules. Option B is wrong because variable names cannot contain spaces; 'var name' includes a space, which is not a valid character in identifiers. Option C is wrong because variable names cannot contain hyphens; 'var-name' uses a hyphen, which Python interprets as the subtraction operator, not part of a name.

11
MCQeasy

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

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

Raising an exception is the standard way to handle invalid input.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

12
MCQhard

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

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

Correct; outer increments after inner loop completes.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

13
MCQmedium

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

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

The else clause returns a string literal, so result is a string.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

14
Matchingmedium

Match each Python control flow statement to its purpose.

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

Concepts
Matches

Exits the current loop immediately

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

Does nothing; used as a placeholder

Short for else-if; checks another condition

Executes a block when no previous condition is true

Why these pairings

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

15
Multi-Selecthard

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

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

Correct.

Why this answer

The `not` operator is a logical operator in Python that returns the Boolean negation of its operand: if the operand is `True`, `not` returns `False`, and vice versa. This is fundamental to Boolean logic and conditional expressions in Python.

Exam trap

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

16
MCQeasy

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

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

Correct negative indexing.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

17
MCQmedium

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

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

Correct: num = num * 2 just rebinds num, not the list.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

18
MCQeasy

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

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

Incompatible types for +.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

19
MCQmedium

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

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

String '5' multiplied by 2 gives '55'.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

20
MCQeasy

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

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

Correct: // with two ints returns int.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

21
Drag & Dropmedium

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

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

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

Why this order

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

22
MCQeasy

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

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

Correct because the default greeting is used.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

23
MCQmedium

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

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

Correct as described.

Why this answer

The string 'Hello World' is first operated on by replace('o', '0') which replaces all occurrences of 'o' with '0', resulting in 'Hell0 W0rld'. Then .upper() converts all characters to uppercase, yielding 'HELL0 W0RLD'. Therefore, option C is correct.

Option A is 'hell0 w0rld' which would require .lower() after replace. Option B is 'HELLO WORLD' which does not apply the replacement. Option D is 'Hell0 W0rld' which is only the result after replace but without .upper().

Exam trap

This question tests chaining string methods. A common mistake is to confuse the order of operations or to forget that replace is case-sensitive (only replaces lowercase 'o').

24
MCQmedium

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

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

Correct.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

25
Multi-Selectmedium

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

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

values returns a view of dictionary values.

Why this answer

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

Exam trap

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

26
MCQmedium

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

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

Selective exception handling allows graceful continuation.

Why this answer

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

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

27
MCQhard

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

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

input() returns string; convert to int first.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

28
MCQmedium

Refer to the exhibit. What is the output when the following code is executed: print(calculate_discount(100, 0.6))

A.Discount too high
B.40.0
C.100
D.Discount too high followed by 100
AnswerD

The print statement outputs the message, then the function returns 100 which is printed.

Why this answer

The code defines a function `calculate_discount(price, discount)` that first checks if the discount is 0.6 or higher. Since 0.6 is exactly equal to 0.6, the condition `if discount >= 0.6` is true, so it prints 'Discount too high' and then returns the original price (100). The `print()` statement outside the function outputs the return value, which is 100, resulting in the output 'Discount too high' followed by '100' on the next line.

Exam trap

The PCEP exam often tests the distinction between a function's printed output and its return value, leading candidates to overlook that both the print inside the function and the print of the return value appear in the output.

How to eliminate wrong answers

Option A is wrong because it only shows 'Discount too high' and omits the returned value 100, which is also printed. Option B is wrong because 40.0 would be the result if the discount were applied (100 * 0.4), but the condition triggers the early return without applying the discount. Option C is wrong because it shows only 100, ignoring the printed message 'Discount too high' that occurs before the return.

29
MCQeasy

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

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

This is the typical cause of a NameError in Python.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

30
Multi-Selecteasy

Which TWO of the following are valid Python data types?

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

String type.

Why this answer

(str) is correct because Python uses 'str' as its built-in type for textual data, which is a sequence of Unicode characters. This is a fundamental data type in Python, distinct from other languages that might use 'string' or 'char'.

Exam trap

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

31
MCQmedium

A list contains strings and numbers: items = ['apple', 10, 'banana', 20]. A programmer wants to create a new list that contains only the strings. Which approach is correct?

A.[item for item in items if item.isdigit()]
B.[item for item in items if type(item) is 'str']
C.[item for item in items if type(item) == str]
D.[item for item in items if isinstance(item, str)]
AnswerD

Correct. The `isinstance()` function checks if an item is an instance of a specified class and is the standard way to test for type.

Why this answer

The `isinstance(item, str)` function is the recommended way to check if an item is a string because it handles inheritance and is more readable. Option C, `type(item) == str`, also works in this case but is not considered the best practice for type checking in Python, especially when dealing with subclasses. Option A uses `isdigit()`, which only works for strings that represent digits, not all strings.

Option B uses `type(item) is 'str'`, which compares the type to a string literal, which is incorrect.

Exam trap

Python Institute often tests the distinction between comparing a type object to a string literal (e.g., `type(item) is 'str'`) versus comparing to the actual type object (e.g., `type(item) == str`), trapping candidates who mistakenly think `'str'` is the same as `str`.

How to eliminate wrong answers

Option A is wrong because `isdigit()` is a string method that checks if a string consists only of digits; it would raise an `AttributeError` when called on an integer (e.g., 10) since integers do not have an `isdigit()` method. Option B is wrong because `type(item) is 'str'` compares the type object to a string literal `'str'`, which will always be `False` since `type(item)` returns a type object (e.g., `<class 'str'>`), not a string.

32
MCQeasy

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

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

Floor division of 5 by 2 yields 2.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

33
MCQmedium

A company stores employee data as a list of dictionaries. Each dictionary has keys 'name' and 'age'. Which code correctly counts employees older than 30?

A.count = 0 for i in range(len(employees)): if employees[i]['age'] <= 30: count += 1
B.count = 0 i = 0 while i < len(employees): if employees[i]['age'] > 30: count += 1
C.count = 0 for emp in employees: if emp['age'] > 30: count += 1
D.count = [emp for emp in employees if emp['age'] > 30]
AnswerC

Correctly increments count for each employee over 30.

Why this answer

It uses a simple `for` loop to iterate directly over each dictionary in the `employees` list, checks if the value of the `'age'` key is greater than 30, and increments the counter accordingly. This is the most Pythonic and readable approach for counting elements that satisfy a condition.

Exam trap

Python Institute often tests the distinction between creating a filtered list and counting elements, so the trap here is that option D looks correct but produces a list instead of a numeric count, which is a subtle but critical difference.

How to eliminate wrong answers

Option A is wrong because it counts employees whose age is <= 30 (the condition is reversed) and uses an index-based loop, which is unnecessarily complex. Option B is wrong because it never initializes `count` to 0 (it would raise a `NameError` or use an undefined variable) and also uses a while loop with manual indexing, which is error-prone. Option D is wrong because it creates a list of dictionaries for employees older than 30, not a count; to get the count, you would need to wrap it in `len()`.

34
Multi-Selecthard

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

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

Correct; e.g., 2**3 = 8.

Why this answer

The ** operator in Python is used for exponentiation, raising the left operand to the power of the right operand. For example, 2 ** 3 evaluates to 8. This is a fundamental arithmetic operator defined in Python's operator precedence.

Exam trap

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

35
MCQeasy

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

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

Adds the number value instead of 1, giving the correct sum.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

36
Multi-Selecthard

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

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

Correct. Python lists are heterogeneous containers; they can store elements of different data types.

Why this answer

Only two options are correct: A and E. Option A is correct because Python lists can contain elements of different data types. Option E is correct because len() returns the number of elements in a list.

Options B, C, D are incorrect: B is wrong because lists are mutable and unhashable, hence cannot be dictionary keys; C is wrong because index starts at 0; D is wrong because lists are mutable.

Exam trap

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

37
MCQmedium

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

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

Correct: 2**3 = 8, 8+4 = 12.

Why this answer

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

Option B is correct.

Exam trap

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

How to eliminate wrong answers

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

38
MCQhard

What is the output of this code?

A.RuntimeError: dictionary changed size during iteration
B.{}
C.{'b': 2}
D.{'a': 1, 'c': 3}
AnswerA

Modifying dict while iterating over its items raises RuntimeError.

Why this answer

Modifying a dictionary's size (adding or deleting keys) during iteration over its keys, values, or items raises a RuntimeError. In this code, the loop iterates over the dictionary's keys while deleting them, which changes the dictionary's size and triggers the exception.

Exam trap

Python Institute often tests the misconception that deleting keys during iteration will silently skip or partially modify the dictionary, but Python explicitly forbids size changes during iteration to enforce safe iteration contracts.

How to eliminate wrong answers

Option B is wrong because the code never completes execution to produce an empty dictionary; the RuntimeError is raised before any deletion finishes. Option C is wrong because the loop is interrupted by the exception before it can delete all keys except 'b', so no partial result is returned. Option D is wrong because the original dictionary is never returned; the iteration is aborted at the first deletion, and the exception prevents any output.

39
MCQhard

A junior developer created a Python script to calculate the average of three quiz scores entered by the user. The script reads three numbers using input(), converts them to float, calculates the sum, and divides by 3. However, when a user enters a non-numeric value like 'ten', the script crashes with a ValueError. The developer needs to modify the script to handle such errors gracefully, allowing the user to re-enter the invalid input until a valid number is provided. Which approach should the developer implement to meet this requirement most effectively while following Python best practices?

A.Implement a while True loop that attempts to convert the input inside a try block. If successful, break out of the loop; if ValueError occurs, print an error message and continue the loop.
B.Use an if statement to check if the input is numeric using .isdigit(), and if not, ask again.
C.Use a try-except block to catch ValueError and prompt the user again, looping until valid input is provided.
D.Use a function that returns a default value of 0 if the input is invalid, to avoid script crashes.
AnswerA

This is the standard pattern for input validation, handling both integers and floats.

Why this answer

It uses a `while True` loop with a `try` block to repeatedly attempt conversion of user input to `float`. If a `ValueError` is raised (e.g., for non-numeric input like 'ten'), the exception is caught, an error message is printed, and the loop continues until valid input is provided. This pattern follows Python best practices for input validation by separating the conversion logic from the loop control and avoiding reliance on fragile string checks like `.isdigit()`.

Exam trap

Python Institute often tests the distinction between a single try-except (which only catches one error) and a looped try-except (which retries until valid input is given), leading candidates to pick Option C because it mentions 'try-except' and 'looping' but lacks the explicit `while True` structure required for repeated prompting.

How to eliminate wrong answers

Option B is wrong because `.isdigit()` only checks for digits (0-9) and will reject valid float inputs like '3.14' or '-5', causing false negatives; it also does not handle negative numbers or decimal points. Option C is wrong because it describes a generic try-except loop but lacks the explicit `while True` structure needed to repeatedly prompt the user until valid input is entered — without the loop, the script would only catch the error once and then continue, potentially crashing again. Option D is wrong because returning a default value of 0 silently masks invalid input, which can lead to incorrect calculations and does not meet the requirement of allowing the user to re-enter the invalid input.

40
MCQhard

Refer to the exhibit. What is the output?

A.{'key': 'old_value'}
B.{'another': 'dict'}
C.None
D.{'key': 'new_value'}
AnswerD

Correct. The original dictionary is mutated.

Why this answer

The `update()` method on a dictionary modifies the dictionary in place by updating the value for an existing key. Since `my_dict` already contains the key `'key'`, calling `update({'key': 'new_value'})` changes its value to `'new_value'`, and the method returns `None`. The print statement outputs the updated dictionary, which is `{'key': 'new_value'}`.

Exam trap

The PCEP exam often tests the distinction between a method's return value and the object it modifies, leading candidates to mistakenly think the output is `None` (the return value of `update()`) instead of the updated dictionary itself.

How to eliminate wrong answers

Option A is wrong because it shows the old value `'old_value'`, but the `update()` method replaces the value for the existing key, so the output reflects the new value. Option B is wrong because it shows a completely different dictionary `{'another': 'dict'}`, which would only appear if the `update()` method were called with a different key or if the dictionary were reassigned entirely. Option C is wrong because although `update()` returns `None`, the print statement prints `my_dict` itself, not the return value of `update()`, so the output is the updated dictionary, not `None`.

41
MCQeasy

A developer writes a loop to sum numbers from 1 to 10. The code outputs 55, but the expected sum is 55. However, the loop uses a range that includes 0. Which range should be used to achieve the correct sum?

A.range(0,11)
B.range(1,11)
C.range(0,101)
D.range(1,10)
AnswerB

Correctly generates 1..10

Why this answer

(range(1,11)) is correct because range(start, stop) generates numbers from start inclusive to stop exclusive. To sum numbers 1 through 10, the range must start at 1 and end at 11 (so 10 is included). The loop that used range(0,11) included 0, but since adding 0 does not change the sum, the output was still 55 — however, the question asks for the range that achieves the correct sum without including unnecessary values.

Exam trap

Python Institute often tests the exclusive nature of range()'s stop parameter, tricking candidates into thinking range(1,10) includes 10 or that range(0,11) is equivalent to range(1,11) when the sum is unchanged by zero.

How to eliminate wrong answers

Option A is wrong because range(0,11) includes 0, which is unnecessary and could cause issues if the sum were expected to exclude zero (though here it didn't affect the result). Option C is wrong because range(0,101) would sum numbers 0 through 100, producing 5050, not 55. Option D is wrong because range(1,10) generates numbers 1 through 9, missing 10, so the sum would be 45, not 55.

42
MCQmedium

Refer to the exhibit. What is the output?

A.A C D
B.B C D
C.A B C D
D.A C
AnswerA

Correct. First 'A', then 'C', then 'D'.

Why this answer

The code defines a tuple containing numbers 1, 3, and 4 (e.g., `t = (1, 3, 4)`) and a dictionary `d = {'A': 1, 'B': 2, 'C': 3, 'D': 4}`. The `for` loop iterates over dictionary keys. The condition `if d[k] in t` checks if the associated value is in the tuple.

Values 1, 3, and 4 are present, so keys A, C, and D are printed. Value 2 is absent, so B is not printed. The output is A, C, D each on a new line, matching option A.

Exam trap

A common pitfall in Python PCEP exams is that dictionary iteration yields keys, but candidates may mistakenly think it yields values, or that the `in` operator checks keys rather than values, leading to incorrect filtering.

How to eliminate wrong answers

Option A (A, C, D) is wrong because it omits 'B', but the value 2 for key 'B' is in the tuple (1,2,3,4,5), so 'B' should be printed. Option B (B, C, D) is wrong because it omits 'A', but the value 1 for key 'A' is in the tuple, so 'A' should be printed. Option D (A, C) is wrong because it omits both 'B' and 'D', but both values 2 and 4 are in the tuple, so 'B' and 'D' should be printed.

43
Multi-Selectmedium

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

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

Truncates float to integer 1.

Why this answer

`int(1.0)` explicitly converts the float `1.0` to an integer by truncating the decimal part, yielding the integer `1`. This is a standard type conversion function in Python.

Exam trap

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

44
MCQmedium

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

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

i=1 is skipped.

Why this answer

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

Option B is correct.

Exam trap

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

How to eliminate wrong answers

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

45
MCQhard

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

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

nonlocal allows modification.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

46
MCQmedium

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

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

List comprehension creates a new list with increments, original unchanged.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

47
MCQhard

A company is developing a data processing pipeline that must handle large datasets efficiently. They notice that using a list comprehension to filter data is slower than expected. Which alternative approach would likely improve performance?

A.Using the map() function
B.Using a for loop with append
C.Using a generator expression
D.Using a lambda function
AnswerC

Generators yield items one by one and avoid storing the entire list, reducing memory and often improving speed.

Why this answer

Generator expressions produce items lazily, one at a time, without storing the entire filtered result in memory. This reduces memory overhead and can improve performance when processing large datasets, as the pipeline can iterate over generated items without building a full list first.

Exam trap

The PCEP exam often tests the misconception that map() or lambda functions are inherently faster for filtering, when in fact the key performance difference lies in lazy evaluation versus eager list construction, which is the core advantage of generator expressions.

How to eliminate wrong answers

Option A is wrong because map() applies a function to every item in an iterable and returns a map object, but it does not inherently filter data; filtering requires additional logic (e.g., combining with filter()), and map() still produces an iterator, not a performance gain over list comprehensions for filtering. Option B is wrong because using a for loop with append is typically slower than a list comprehension due to the overhead of repeated method calls and dynamic list resizing, making it a less efficient alternative. Option D is wrong because a lambda function is just an anonymous function definition; it does not by itself improve performance—it must be used with other constructs like map() or filter(), and the performance characteristics depend on the surrounding code, not the lambda itself.

48
MCQeasy

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

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

TypeError occurs when an operation is applied to an object of inappropriate type. However, multiplying integer by string is permitted for repetition, so no TypeError.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

49
MCQeasy

Which of the following is a valid floating-point literal in Python?

A.1e3
B.'3.14'
C.3.14
D.0xFF
AnswerA, C

1e3 is a floating-point literal because the 'e' introduces an exponent, making it a float.

Why this answer

Both 1e3 and 3.14 are valid floating-point literals in Python. 1e3 uses scientific notation with an exponent, which Python interprets as a float. 3.14 is a literal with a decimal point. Options B and D are string and integer literals, respectively.

Exam trap

A common trap is that candidates may think 1e3 is not a floating-point literal because it lacks a decimal point, but in Python, any numeric literal with an exponent is a floating-point literal. Also, candidates may confuse string or hexadecimal literals with float literals.

How to eliminate wrong answers

Option A is wrong because `1e3` is a valid floating-point literal (it represents 1000.0 in scientific notation), but the question asks for a valid floating-point literal and this option is not marked as correct; however, the trap is that `1e3` is actually valid, so candidates might think it is wrong when it is not—but in this set, C is the only one that is unambiguously a float literal without scientific notation. Option B is wrong because `'3.14'` is a string literal, not a floating-point literal; it is enclosed in quotes, making it a sequence of characters. Option D is wrong because `0xFF` is an integer literal in hexadecimal notation (255 in decimal), not a floating-point literal; Python does not allow hexadecimal notation for floats.

50
MCQeasy

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

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

Correct iteration and method call.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

51
MCQhard

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

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

Correct due to aliasing.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

52
Multi-Selecteasy

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

Select 2 answers
A.total$
B.data1
C.my var
D._count
E.2nd_place
AnswersB, D

Valid: letters and digits allowed.

Why this answer

'data1' starts with a letter and contains only letters and digits, which is allowed by Python's identifier rules. Python variable names must begin with a letter (a-z, A-Z) or underscore, and can be followed by letters, digits, or underscores.

Exam trap

Python Institute often tests the rule that variable names cannot start with a digit, and candidates mistakenly think digits are allowed anywhere, or they overlook that special characters like $ are invalid in Python (unlike in some other languages like PHP or Perl).

53
MCQhard

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

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

Integer division by zero raises ZeroDivisionError.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

Only division by zero triggers a runtime exception.

54
MCQeasy

A system administrator has a Python script that uses a tuple to store immutable configuration parameters, such as server address and port. A new business requirement arises: one of these parameters (the port number) must be changeable at runtime without restarting the script. The other parameters must remain immutable. The administrator wants to minimize changes to the existing codebase and maintain clarity. Which approach best satisfies the requirement while keeping the code maintainable?

A.Use a namedtuple and use the _replace() method to create a new instance with the updated port
B.Replace the entire tuple with a list to allow updates
C.Store all parameters in a dictionary and update the port as needed
D.Convert the tuple to a list, update the port, then convert back to a tuple each time
AnswerC

A dictionary is mutable and allows easy updates while clearly showing which parameters are changeable.

Why this answer

A dictionary allows direct mutation of the port value without affecting the immutability of other parameters. This satisfies the requirement of changing only the port at runtime while keeping the rest of the configuration unchanged, and it minimizes code changes by simply replacing the tuple with a dict and using assignment to update the port key.

Exam trap

The trap here is that candidates assume namedtuple._replace() mutates the tuple in place, but it actually returns a new instance, which does not satisfy the requirement for runtime mutation without restarting the script.

How to eliminate wrong answers

Option A is wrong because namedtuple._replace() creates a new namedtuple instance, which does not mutate the original tuple; this approach still requires reassigning the variable and does not allow in-place mutation of a single element, so it does not meet the 'changeable at runtime' requirement without restarting the script. Option B is wrong because replacing the entire tuple with a list makes all parameters mutable, violating the requirement that other parameters remain immutable. Option D is wrong because repeatedly converting between tuple and list is inefficient, adds unnecessary complexity, and still makes all parameters mutable during the list phase, breaking immutability for the other parameters.

55
MCQhard

A network configuration tool stores device settings in a dictionary where each setting key may have multiple values from different configuration sources. For example, the key 'dns_servers' might have values from the DHCP server and manual configuration. The current implementation simply assigns values: settings[key] = value. If the same key appears multiple times, only the last value is kept, losing previous values. The developer must modify the data structure so that all values for a key are preserved. The solution should be efficient for both adding new values and accessing all values for a key. Which modification is best?

A.Use a set for each value to avoid duplicates
B.Use a dictionary of lists with a default factory (e.g., collections.defaultdict(list))
C.Use a list for each value, and append new values to the list
D.Use a tuple for each value, converting to list when needed
AnswerB

Using a dictionary of lists with a default factory (e.g., collections.defaultdict(list)) automatically creates a new list for each new key, allowing multiple values to be appended without overwriting. This preserves all values for a key efficiently for both adding and retrieving.

Why this answer

`collections.defaultdict(list)` automatically creates a new list for each new key, allowing multiple values to be appended without overwriting. This preserves all values for a key while providing O(1) average-time access to the list of values, meeting the efficiency requirement for both adding and retrieving.

Exam trap

The trap here is that candidates think Option C is sufficient on its own, overlooking that `defaultdict` provides automatic initialization, which is the key efficiency improvement tested in the PCEP exam.

How to eliminate wrong answers

Option A is wrong because using a set for each value would deduplicate entries, which is not required and would lose legitimate duplicate values from different sources (e.g., the same DNS server from DHCP and manual config). Option C is wrong because while appending to a list works, it requires manually checking if the key exists and initializing a list for each new key, which is less efficient and more error-prone than using a defaultdict. Option D is wrong because tuples are immutable; converting to a list for each append operation introduces unnecessary overhead and complexity, and the tuple would need to be replaced entirely on each addition.

56
MCQeasy

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

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

Python cannot concatenate string and int without conversion.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

57
MCQhard

You are maintaining a legacy Python 2.7 script that calculates shipping costs. The script reads weight from user input, then calculates cost as weight * 1.5. Recently, the company upgraded to Python 3.9, and now the script raises a TypeError: can't multiply sequence by non-int of type 'float'. The input line is: weight = input('Enter weight: '). You need to fix the script minimally. Which action should you take?

A.Use Python 2 style input by importing from __future__
B.Change the multiplication to cost = float(weight) * 1.5
C.Change the input line to weight = int(input('Enter weight: '))
D.Change the input line to weight = float(input('Enter weight: '))
AnswerD

Converts string to float, allowing multiplication.

Why this answer

In Python 3.9, `input()` returns a string, not a number. Multiplying a string by a float raises a TypeError. Option D converts the input to a float immediately, which is the minimal fix because it handles both integer and decimal weights correctly without changing the multiplication logic.

Exam trap

Python Institute often tests the difference between Python 2 and Python 3 `input()` behavior, and the trap here is that candidates might choose `int()` (Option C) thinking weights are always whole numbers, or choose `from __future__` (Option A) without realizing it does not fix the type mismatch in Python 3.

How to eliminate wrong answers

Option A is wrong because `from __future__` imports are for Python 2 compatibility in Python 3, but here the script is already running on Python 3.9 and the issue is type mismatch, not input behavior. Option B is wrong because it converts `weight` to float only in the multiplication line, but `weight` remains a string; this would still fail if `weight` is used elsewhere as a string, and it does not fix the root cause of the input being a string. Option C is wrong because using `int()` would reject decimal weights (e.g., 2.5), causing a ValueError, and the problem statement does not restrict weights to integers.

58
MCQmedium

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

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

Correct; exact concatenation.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

59
MCQeasy

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

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

Correct. The dash separates the two words.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

60
MCQeasy

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

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

Floor division returns the integer part, 3.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

61
MCQhard

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

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

Correct: set provides fast membership and uniqueness.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

62
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

63
MCQeasy

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

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

Catches ValueError and allows reprompt.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

64
MCQhard

You are a developer in a data science team using Python for analysis. A colleague wrote a script that downloads a CSV file from a URL, parses it using csv.DictReader, and prints summary statistics. The script works on his machine but fails on yours with 'UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 100: invalid continuation byte'. The CSV file contains text in multiple languages, including French accents. The error occurs in the csv.DictReader call. You need to fix the script to work on any machine. Which approach is best?

A.Read the file in binary mode and decode with 'utf-8' ignoring errors.
B.Open the file with encoding='utf-8-sig' to handle BOM.
C.Use the errors='replace' parameter in the open() call.
D.Open the file with encoding='latin-1' (or 'cp1252') to handle a wider range of bytes.
AnswerD

latin-1 can decode any byte, preserving data, though may not be accurate for all characters.

Why this answer

The error indicates the CSV file contains bytes that are not valid UTF-8, such as 0xe9 (é in Latin-1). Opening the file with encoding='latin-1' (or 'cp1252') maps every byte to the corresponding Unicode code point without decoding errors, which is a practical fix for CSV files with mixed-language text that are not strictly UTF-8. This approach ensures the file can be read on any machine regardless of the default system encoding.

Exam trap

The PCEP exam often tests the misconception that 'utf-8-sig' or error-handling parameters like 'ignore' or 'replace' are universal fixes, when in fact they either address a different problem (BOM) or corrupt data, whereas specifying the correct encoding (latin-1) is the proper solution for files with extended Latin characters.

How to eliminate wrong answers

Option A is wrong because reading in binary mode and decoding with 'utf-8' ignoring errors silently discards problematic bytes, corrupting the data and potentially breaking CSV parsing. Option B is wrong because 'utf-8-sig' only handles a UTF-8 BOM (Byte Order Mark) at the start of the file, but the error here is caused by non-UTF-8 bytes in the middle of the file, not a BOM issue. Option C is wrong because errors='replace' replaces undecodable bytes with the replacement character (U+FFFD), which alters the data and can introduce invalid characters that break CSV parsing or produce incorrect statistics.

65
Multi-Selecthard

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

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

List comprehension.

Why this answer

It uses a list comprehension with `range(1,4)`, which generates the numbers 1, 2, and 3 and collects them into a new list. This is a concise and valid Python syntax for creating a list from an iterable.

Exam trap

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

66
MCQmedium

A developer is writing a script to process user input. The script should repeatedly ask for a number until a valid integer is entered. Which loop structure is most appropriate?

A.while loop with a condition
B.for loop
C.do-while loop
D.Recursion
AnswerA

A while loop can run until a condition is met, ideal for input validation.

Why this answer

A while loop with a condition is the most appropriate because it allows the script to repeatedly prompt for input until a valid integer is entered, checking the condition before each iteration. In Python, the while loop continues as long as the condition evaluates to True, making it ideal for indefinite iteration where the number of repetitions is unknown beforehand. This pattern is commonly used with a try-except block to validate integer conversion.

Exam trap

The PCEP exam often tests the misconception that a for loop can handle indefinite repetition by using a large range, but the trap is that for loops are designed for definite iteration over a sequence, not for conditions that depend on runtime input validation.

How to eliminate wrong answers

Option B (for loop) is wrong because a for loop iterates over a fixed sequence (e.g., a range or list), which is unsuitable for an unknown number of repetitions until valid input is received. Option C (do-while loop) is wrong because Python does not have a built-in do-while loop; the concept exists in other languages but cannot be directly used in Python without emulating it with a while loop. Option D (Recursion) is wrong because while recursion could theoretically work, it risks hitting Python's recursion limit (default 1000) and is less efficient and harder to read than a simple while loop for this repetitive input validation task.

67
MCQmedium

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

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

Step by step: not (True) and (True) = False.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

68
MCQhard

Refer to the exhibit. What is the output?

A.1 2 --- 1
B.1 2 3 --- 1
C.1 2 3 --- 1 2 3
D.1 --- 1
AnswerB

Correct. First loop prints all three, second loop prints only first then breaks.

Why this answer

The code defines a tuple t = (1, 2, 3) and iterates over it with a single for loop, printing each element on a separate line. After the loop, it prints a separator line of dashes (---) and then prints the first element t[0] which is 1. The output is therefore 1, 2, 3, ---, 1 — exactly matching option B.

Exam trap

The PCEP exam often tests the distinction between iterating over all elements of a tuple versus accessing a single element by index, leading candidates to mistakenly think the final print repeats the entire loop or that the loop stops early.

How to eliminate wrong answers

Option A is wrong because it omits the third element `3` from the loop output, suggesting the loop only iterated twice or that the tuple had only two elements. Option C is wrong because it prints `1 2 3` again after the separator, implying the loop ran again or that the final print statement iterated over the entire tuple instead of accessing only index 0. Option D is wrong because it shows only the first element `1` from the loop and then the final `1`, completely missing the second and third elements, as if the loop only executed once or the tuple contained only one element.

69
MCQhard

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

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

Correct: y*2=10, x+=10 yields 20, y unchanged.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

70
Multi-Selecteasy

Which TWO of the following are valid Python variable names?

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

Underscore allowed at start.

Why this answer

(_count) is correct because Python allows variable names to start with an underscore, and it contains only letters, underscores, and digits. Underscore-prefixed names are commonly used for internal or private variables, but they are syntactically valid.

Exam trap

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

71
MCQhard

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

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

Concise and idiomatic list comprehension.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

72
MCQmedium

You are writing a script to parse a log file. Each line in the log contains a timestamp and a message separated by a colon. You need to extract only the messages that contain the word 'ERROR'. The script uses a list comprehension to filter lines. However, the script crashes with a 'ValueError: not enough values to unpack' when processing some lines. The code is: lines = ['2024-01-01 12:00:00: INFO: all good', '2024-01-01 12:01:00: ERROR: something wrong'] errors = [msg for timestamp, msg in line.split(': ') for line in lines if 'ERROR' in msg] What is the correct fix?

A.Rewrite as: [line for line in lines if 'ERROR' in line]
B.Change the list to a dictionary
C.Swap the order of the for clauses to: [msg for line in lines for timestamp, msg in line.split(': ') if 'ERROR' in msg]
D.Rewrite as: [msg for line in lines if 'ERROR' in line for msg in [line.split(': ')[1]]]
AnswerD

Correct nested comprehension.

Why this answer

It properly separates the filtering and unpacking steps. The original code attempts to unpack each line into timestamp and msg using `line.split(': ')`, but some lines may not contain exactly two parts after splitting (e.g., if the colon is missing or there are extra colons), causing a ValueError. Option D first filters lines containing 'ERROR', then safely extracts the message part by splitting and taking index [1] inside a nested comprehension, avoiding the unpacking error.

Exam trap

Python Institute often tests the order of `for` clauses in nested list comprehensions and the assumption that `split()` always returns a fixed number of parts, leading candidates to choose Option C which only reorders loops without fixing the unpacking error.

How to eliminate wrong answers

Option A is wrong because it returns the entire line as a string, not just the message part after the colon, so it does not meet the requirement of extracting only the messages. Option B is wrong because converting the list to a dictionary does not solve the unpacking issue; the original code would still crash on lines that cannot be split into exactly two parts. Option C is wrong because swapping the for clauses does not fix the fundamental problem: `line.split(': ')` still returns a list that may not have exactly two elements, and unpacking it into timestamp, msg will raise a ValueError if the split result has a different length.

73
Multi-Selecteasy

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

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

Sorts the list in place.

Why this answer

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

Exam trap

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

74
MCQmedium

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

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

Correct; checks if 8080 is in the list.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

75
Multi-Selecthard

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

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

Tuples cannot be changed after creation.

Why this answer

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

Exam trap

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

Page 1 of 7

Page 2

All pages