Courseiva

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

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

Page 4

Page 5 of 7

Page 6
301
MCQhard

Refer to the exhibit. A developer runs this code. What is printed?

A.Running in normal mode
B.Error
C.True
D.Debug mode active
AnswerA

Since debug is False, the else branch runs.

Why this answer

The code first checks a variable `debug`. Since `debug` is likely `False` or not set (default), the condition `if debug:` is `False`, so it moves to the `elif` branch. The condition `if __name__ == '__main__':` evaluates to `True` because the script is run directly, so it prints 'Running in normal mode'.

This is the standard Python entry-point pattern for conditional execution of code only when the script is executed directly.

Exam trap

The PCEP exam often tests the `if __name__ == '__main__':` idiom to see if candidates understand that `__name__` is `'__main__'` only when the script is run directly, not when imported.

How to eliminate wrong answers

Option B is wrong because there is no syntax error or runtime error in the code; the `if` statement and `print` function are valid. Option C is wrong because the code does not print the boolean `True`; it prints a string based on the condition. Option D is wrong because the code does not define or check any debug flag; the string 'Debug mode active' is never printed.

302
Multi-Selectmedium

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

Select 3 answers
A.float
B.list
C.char
D.dict
E.record
AnswersA, B, D

Built-in numeric type.

Why this answer

A is correct because `float` is a built-in Python numeric data type used to represent floating-point numbers (e.g., 3.14, -0.001). It is one of the core immutable types in Python, distinct from integers and complex numbers.

Exam trap

Python Institute often tests the distinction between Python's built-in types and types from other languages (like `char` or `record`) to catch candidates who assume Python has a dedicated character type or who confuse database terminology with Python data structures.

303
MCQhard

A script calculates total cost: price = 49.95, quantity = 3, tax_rate = 0.08. The developer writes: total = price * quantity * (1 + tax_rate). The result is printed as 161.838. Which best practice is being violated?

A.Using parentheses unnecessarily.
B.Not using an f-string to format the output.
C.Not rounding the result to two decimal places for currency.
D.Using multiplication instead of addition for tax.
AnswerC

Currency should be rounded to avoid floating-point imprecision.

Why this answer

When dealing with currency values, best practice dictates rounding to two decimal places to represent cents. The raw result 161.838 is not a valid monetary amount; it should be rounded to 161.84 using `round(total, 2)` or formatted with `:.2f`. This ensures accuracy and avoids confusion in financial calculations.

Exam trap

Python Institute often tests the misconception that any arithmetic result is acceptable as long as the formula is correct, but the trap is that currency values require explicit rounding to two decimal places to follow financial best practices.

How to eliminate wrong answers

Option A is wrong because the parentheses are necessary to ensure the tax multiplier (1 + tax_rate) is computed before multiplication; without them, the expression would be evaluated incorrectly due to operator precedence. Option B is wrong because using an f-string is a formatting preference, not a best practice violation; the core issue is the lack of rounding, not the output method. Option D is wrong because the tax calculation correctly uses multiplication to apply the tax rate as a percentage; addition would incorrectly add a flat value instead of a proportional tax.

304
MCQmedium

A developer needs to read an integer from user input and store it. Which code snippet accomplishes this?

A.x = int(input())
B.x = read_int()
C.x = input(int())
D.x = int(input)
AnswerA

Correct; input() returns string, int() converts.

Why this answer

`int(input())` first calls `input()` to read a string from the user, then passes that string to `int()` to convert it to an integer. This is the standard Python pattern for reading an integer from standard input.

Exam trap

Python Institute often tests the distinction between calling a function (with parentheses) and referencing it (without parentheses), so candidates mistakenly write `int(input)` instead of `int(input())`.

How to eliminate wrong answers

Option B is wrong because `read_int()` is not a built-in Python function; it would raise a NameError unless explicitly defined. Option C is wrong because `input(int())` attempts to call `int()` with no argument (which returns 0) and then passes that integer to `input()`, which expects a string prompt, causing a TypeError. Option D is wrong because `int(input)` passes the function object `input` (not its result) to `int()`, which raises a TypeError since `int()` expects a string or number, not a function.

305
Multi-Selecthard

Which THREE of the following expressions evaluate to True?

Select 3 answers
A.10 / 2 == 5.0
B.10 // 2 == 5
C.10 % 2 == 0
D.10 // 2 == 5.1
E.10 % 2 == 1
AnswersA, B, C

True. Division yields 5.0.

Why this answer

The division operator `/` in Python always returns a float. Since 10 divided by 2 equals 5.0, and the comparison `==` checks value equality (not type), `5.0 == 5.0` evaluates to True.

Exam trap

Python Institute often tests the distinction between `/` (true division returning float) and `//` (floor division returning int), and the fact that modulo with even numbers always yields 0, tricking candidates who confuse remainder with quotient.

306
Multi-Selecteasy

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

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

Valid.

Why this answer

(my_var) is correct because Python variable names can contain letters, digits, and underscores, but must not start with a digit. 'my_var' follows all naming rules: it starts with a letter, uses an underscore, and contains no invalid characters.

Exam trap

Python Institute often tests the rule that hyphens are invalid in variable names (tricking candidates who confuse them with underscores) and that keywords like 'class' cannot be used as identifiers, even though they look like valid names.

307
MCQhard

Consider the code: try: try: raise TypeError except ValueError: print('A') except TypeError: print('B') finally: print('C'). What is printed?

A.A, B, and C
B.C only
C.B and C
D.A and C
AnswerC

Correct: Outer except catches TypeError, then finally runs.

Why this answer

The inner `try` raises a `TypeError`. The inner `except ValueError` does not catch it, so the exception propagates to the outer `except TypeError`, which catches it and prints 'B'. The `finally` block always executes, printing 'C'.

Thus, the output is 'B' and 'C'.

Exam trap

The PCEP exam often tests the distinction between exception types and the order of `except` blocks, tricking candidates into thinking a `finally` block suppresses exception propagation or that an inner `except` catches unrelated exception types.

How to eliminate wrong answers

Option A is wrong because it suggests 'A' is printed, but the `except ValueError` does not catch a `TypeError`, so 'A' is never printed. Option B is wrong because it claims only 'C' is printed, ignoring that the `TypeError` is caught by the outer `except TypeError`, which prints 'B'. Option D is wrong because it includes 'A', which is never printed, and omits 'B', which is printed.

308
MCQeasy

A function `def process(data):` modifies the dictionary passed as argument by adding a new key. The developer wants to avoid modifying the original dictionary. What should the function do?

A.Create a copy of the dictionary at the start: `data = data.copy()`
B.Add the key, then delete it at the end.
C.Modify directly; changes to mutable objects are local only.
D.Convert the dictionary to a tuple before processing.
AnswerA

copy() creates a shallow copy, avoiding modification of original.

Why this answer

Dictionaries are mutable objects in Python, so passing a dictionary to a function passes a reference to the same object. Calling `data.copy()` creates a shallow copy of the dictionary, allowing the function to modify the copy without affecting the original dictionary. This is the standard Pythonic way to avoid side effects on mutable arguments.

Exam trap

Python Institute often tests the misconception that mutable objects are passed by value or that changes inside a function are local, leading candidates to incorrectly choose Option C, which is false for mutable types like dictionaries and lists.

How to eliminate wrong answers

Option B is wrong because adding a key and then deleting it at the end still modifies the original dictionary during execution, which defeats the purpose of avoiding modification; the original dictionary is changed temporarily and may cause issues if an exception occurs before deletion. Option C is wrong because changes to mutable objects like dictionaries are not local — they affect the original object outside the function, as Python passes references to mutable objects, not copies. Option D is wrong because converting a dictionary to a tuple is not possible (tuples are immutable sequences, not mappings) and would raise a TypeError; even if converted, the original dictionary remains unmodified, but the approach is invalid and does not solve the problem.

309
MCQhard

A developer is building a simple calculator that accepts two numbers and an operator string. The code: x = float(input("First: ")) y = float(input("Second: ")) op = input("Operator (+, -, *, /): ") if op == "+": result = x + y elif op == "-": result = x - y elif op == "*": result = x * y elif op == "/": result = x / y print("Result:", result) When the user enters 10, 3, and "/", the output is "Result: 3.3333333333333335". The developer wants to display only two decimal places. Which code change will achieve this without introducing errors?

A.Change print to: print("Result:", format(result, ".2f"))
B.Change print to: print("Result: " + str(result)[:4])
C.Change print to: print("Result:", result.toFixed(2))
D.Change print to: print("Result:", round(result, 2))
AnswerA

format with '.2f' always shows exactly two decimal places.

Why this answer

The `format()` function with the format specifier `.2f` converts the floating-point result to a string rounded to two decimal places, which is exactly what the developer needs. This approach does not alter the original variable and works reliably for display purposes.

Exam trap

Python Institute often tests the distinction between rounding a number (which returns a float) and formatting a number for display (which returns a string), and the trap here is that candidates may think `round()` solves the display problem, but it does not guarantee a fixed number of decimal places in the output.

How to eliminate wrong answers

Option B is wrong because slicing the string representation of the result to the first four characters (e.g., '3.33') will fail for numbers with fewer digits before the decimal (e.g., 0.1234 becomes '0.12') or for negative numbers, and it does not perform proper rounding. Option C is wrong because Python does not have a `toFixed()` method; that is a JavaScript method, and using it will raise an AttributeError. Option D is wrong because `round(result, 2)` returns a float, and due to floating-point representation, the printed value may still show many decimal places (e.g., `round(3.3333333333333335, 2)` gives `3.33` but printing it directly may display `3.33` in some environments, but it is not guaranteed to always show exactly two decimal places—for example, `round(2.5, 2)` prints as `2.5`, not `2.50`—so it does not reliably force two decimal places in the output.

310
MCQhard

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

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

x and y refer to the same list, so the append affects both.

Why this answer

In Python, variables hold references to objects, not copies. 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 printing `x` reflects the change and outputs `[1, 2, 3, 4]`.

Exam trap

The PCEP exam often tests the distinction between reference assignment and copying for mutable objects, trapping candidates who assume `y = x` creates an independent copy of the list.

How to eliminate wrong answers

Option B is wrong because the code does not produce an error; `append` is a valid list method and the assignment `y = x` is syntactically correct. Option C is wrong because `[4]` would only be the output if `x` were reassigned to a new list containing only `4`, but here the original list is mutated. Option D is wrong because it assumes `y = x` creates a copy of the list, but Python uses reference semantics for mutable objects, so modifications through `y` affect `x`.

311
MCQmedium

A program contains this code: print(1 and 2 or 3). What is the output?

A.3
B.1
C.True
D.2
AnswerD

Evaluation: 1 and 2 -> 2; 2 or 3 -> 2.

Why this answer

In Python, the `and` and `or` operators short-circuit and return the last evaluated operand, not a boolean. `1 and 2` evaluates to `2` because both are truthy and `and` returns the last truthy value. Then `2 or 3` short-circuits because `2` is truthy, so `or` returns `2` without evaluating `3`. Thus, the output is `2`.

Exam trap

Python Institute often tests the misconception that `and`/`or` always return `True` or `False`, leading candidates to pick `True` (option C) instead of the actual operand value `2`.

How to eliminate wrong answers

Option A is wrong because `3` would only be returned if both `1` and `2` were falsy in an `or` chain, but here `2` is truthy and short-circuits the `or`. Option B is wrong because `1` is not the final result; `and` returns the last truthy operand (`2`), not the first. Option C is wrong because the expression does not return a boolean `True`; it returns the actual operand value `2`, which is truthy but not the boolean `True`.

312
Matchingmedium

Match each Python string method to its action.

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

Concepts
Matches

Converts all characters to uppercase

Converts all characters to lowercase

Removes leading and trailing whitespace

Splits a string into a list of substrings

Joins elements of an iterable into a single string

Why these pairings

These are common string methods used for text manipulation. Correct matches: .upper() converts to uppercase, .lower() to lowercase, .strip() removes leading/trailing whitespace, .split() splits into a list. The distractors swap definitions to test understanding.

313
MCQeasy

The exhibit shows a JSON configuration. Which Python data structure is best suited to represent this configuration?

A.Dictionary
B.Tuple
C.String
D.List
AnswerA

JSON objects map directly to Python dictionaries.

Why this answer

JSON objects map directly to Python dictionaries. Option B (Tuple) is wrong because tuples are immutable and lack key-value mapping. Option C (String) is wrong because a string would lose all structure, making access by key impossible.

Option D (List) is wrong because lists are ordered sequences accessed by index, not by key-value pairs.

314
MCQeasy

A team is reviewing code that uses if-elif-else to classify a test score. They notice that for score 90, it prints 'B' instead of 'A'. Which of the following best explains the issue?

A.The order of conditions does not matter
B.The elif condition should use >= instead of >
C.The condition for 'A' should be checked before 'B'
D.The code uses elif instead of else if
AnswerC

Correct: to print 'A' for scores >= 90, that condition must come first.

Why this answer

In an if-elif-else chain, the first matching condition is executed and the rest are skipped. If the condition for 'A' (e.g., score >= 90) is placed after the condition for 'B' (e.g., score >= 80), a score of 90 will match the 'B' condition first and never reach the 'A' condition. To fix this, the most restrictive condition (highest grade) must be checked first.

Exam trap

Python Institute often tests the misconception that condition order is irrelevant in if-elif-else chains, tempting candidates to pick Option A, when in fact the sequential evaluation makes order crucial.

How to eliminate wrong answers

Option A is wrong because the order of conditions in an if-elif-else chain is critical; Python evaluates them sequentially and executes only the first true branch, so changing order can change the output. Option B is wrong because the issue is not about using > vs >=; even if the 'B' condition used >=, a score of 90 would still match it first if 'A' is checked later. Option D is wrong because elif is the correct Python syntax for 'else if'; using 'else if' would cause a syntax error, and the code runs without error, just with incorrect logic.

315
MCQhard

Consider the code: x = 10; def func(): x = 5; print(x); func(); print(x). What is the output?

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

Local scope inside function, global unchanged outside.

Why this answer

Inside the function `func()`, the local variable `x` is assigned the value 5, so `print(x)` inside the function outputs 5. After the function call, the global `x` remains 10, so the final `print(x)` outside the function outputs 10. This demonstrates Python's scoping rules where assignments inside a function create a local variable unless declared global.

Exam trap

The PCEP exam often tests the misconception that a variable assignment inside a function modifies the global variable, leading candidates to incorrectly choose options where both outputs are the same or the global value is overwritten.

How to eliminate wrong answers

Option B is wrong because it assumes the local assignment `x = 5` also changes the global `x`, which is not true without the `global` keyword. Option C is wrong because it suggests the function never uses its local `x`, outputting 10 twice, which ignores the local assignment. Option D is wrong because it reverses the order, outputting 10 then 5, which would only happen if the global `x` were printed first and then the local `x` after the function call, but the code prints inside the function first.

316
MCQmedium

A developer writes a function that returns multiple values. How should they return these values?

A.return a, b
B.return a+b
C.return [a,b]
D.return a; return b
AnswerA

This returns a tuple containing a and b.

Why this answer

In Python, a function can return multiple values by separating them with commas in the return statement. This automatically packs them into a tuple, which is then unpacked by the caller. Option A correctly uses `return a, b`, which returns a tuple `(a, b)`, allowing the caller to assign the results to separate variables.

Exam trap

The PCEP exam often tests the distinction between returning multiple values as a tuple (comma-separated) versus returning a single container object like a list, tricking candidates who think lists are the only way to return multiple items.

How to eliminate wrong answers

Option B is wrong because `return a+b` returns a single value (the sum of a and b), not multiple separate values. Option C is wrong because `return [a,b]` returns a list object containing a and b, not multiple return values; the function still returns a single object. Option D is wrong because `return a; return b` is syntactically invalid—only the first return statement executes, and the second is unreachable, causing a syntax error or unexpected behavior.

317
MCQeasy

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

A.['abc', 'abc', 'abc']
B.abcabc abc
C.abc abc abc
D.abcabcabc
AnswerD

Correct: repeats string 3 times.

Why this answer

The code `print('abc' * 3)` uses the multiplication operator on a string. In Python, multiplying a string by an integer repeats the string that many times, concatenating the copies without any separator. Therefore, `'abc' * 3` produces the string `'abcabcabc'`, which is printed.

The correct output is `abcabcabc` (without quotes).

Exam trap

The trap here is that candidates often confuse string multiplication with list multiplication or expect spaces between repetitions, but Python's string multiplication concatenates the string directly without any separator.

How to eliminate wrong answers

Option A is wrong because it shows a list with three 'abc' strings, which would be the output if the code used `['abc'] * 3` and printed the list, but the correct code uses string multiplication, not list multiplication. Option B is wrong because it shows 'abcabc abc' with a space, which would result from printing a list or using incorrect concatenation, but string multiplication does not insert spaces. Option C is wrong because it shows 'abc abc abc' with spaces, which would be the output of `print('abc', 'abc', 'abc')` or using `join` with spaces, not string multiplication.

318
MCQhard

Refer to the exhibit. A beginner Python programmer executes the code and gets an error. What is the most likely cause?

A.The variables x and y are of incompatible types for the + operator
B.The + operator cannot be used with print()
C.The variable y should be converted to an integer using int()
D.The print function is misspelled
AnswerA

Correct: int and str cannot be added with +

Why this answer

The error occurs when the + operator is used between incompatible types, such as a string (x) and an integer (y). In Python, the + operator performs concatenation for strings and addition for numbers, but mixing types without explicit conversion raises a TypeError. The code likely defines x as a string (e.g., '10') and y as an integer (e.g., 5), causing the error.

Exam trap

Python Institute often tests the misconception that the + operator can automatically convert types, leading candidates to overlook the need for explicit type conversion or to incorrectly blame the print function.

How to eliminate wrong answers

Option B is wrong because the + operator can be used inside print() to concatenate strings or add numbers, and it is a common and valid usage. Option C is wrong because converting y to an integer using int() would not fix the error if y is already an integer; the issue is that x is a string, not that y needs conversion. Option D is wrong because the print function is correctly spelled in the code (assuming the exhibit shows 'print'), and a misspelling would cause a NameError, not a TypeError from the + operator.

319
MCQmedium

Consider the following function definition: def add(a, b): return a + b What is the value of add(3, '4')?

A.Error due to missing import
B.'34'
C.7
D.TypeError: unsupported operand type(s) for +: 'int' and 'str'
AnswerD

Incompatible types.

Why this answer

Python's `+` operator is not defined for mixed types like `int` and `str`. When `add(3, '4')` is called, Python attempts to evaluate `3 + '4'`, which raises a `TypeError` because it cannot implicitly convert the string to an integer or vice versa. This is a fundamental type safety rule in Python.

Exam trap

The PCEP exam often tests the misconception that Python will implicitly convert types (like treating `'4'` as an integer) or that the `+` operator will concatenate any two values, when in reality it raises a `TypeError` for incompatible types.

How to eliminate wrong answers

Option A is wrong because no import is needed for basic arithmetic or string operations; the error is purely a type mismatch, not a missing module. Option B is wrong because Python does not automatically concatenate an integer and a string with `+`; that would require explicit conversion (e.g., `str(3) + '4'`). Option C is wrong because Python does not implicitly convert the string `'4'` to the integer `4` for addition; the `+` operator is strictly type-specific and raises an error instead.

320
MCQmedium

A programmer writes code that uses a while loop to process user input until the user types 'exit'. The code currently prints 'Done' after the loop, but it never exits. What is the most likely cause?

A.The loop condition is 'while True'
B.The print statement is indented incorrectly
C.The input function is called outside the loop
D.The variable controlling the loop is not updated inside the loop
AnswerD

Classic infinite loop cause.

Why this answer

If the variable controlling the loop (e.g., the user's input) is never updated inside the while loop, the loop condition will never become false, causing an infinite loop. In this scenario, the programmer likely reads input once before the loop but does not call input() again inside the loop to update the variable, so the loop never sees the 'exit' value.

Exam trap

Python Institute often tests the distinction between reading input once versus repeatedly inside a loop, and the trap here is that candidates may think 'while True' is always the cause of an infinite loop, overlooking the fact that a loop variable not being updated is the more precise and common reason.

How to eliminate wrong answers

Option A is wrong because 'while True' creates an infinite loop only if there is no break statement; the question states the loop never exits, but 'while True' with a proper break inside could still exit, so it is not the most likely cause. Option B is wrong because an incorrectly indented print statement would cause a syntax error or unexpected output, not an infinite loop that never exits. Option C is wrong because calling input() outside the loop would read a single value and never update the loop condition, which is essentially the same as D, but D more precisely states that the variable controlling the loop is not updated inside the loop, which is the root cause.

321
MCQhard

A function is designed to return False if a number is not divisible by 2. Which of the following return statements correctly implements this logic?

A.return n % 2 != 0
B.return n % 2 == 1
C.return not n % 2 == 0
D.return n % 2 == 0
AnswerD

Correct. Returns True if divisible, False otherwise, matching the requirement.

Why this answer

The function must return False when the number is not divisible by 2. The expression `n % 2 == 0` evaluates to True when n is even (divisible by 2) and False when n is odd (not divisible by 2), directly matching the required logic.

Exam trap

The trap here is that candidates often confuse the condition for divisibility (n % 2 == 0) with the condition for non-divisibility (n % 2 != 0), leading them to select an option that returns the opposite boolean value.

How to eliminate wrong answers

Option A is wrong because `return n % 2 != 0` returns True when n is not divisible by 2 (odd) and False when divisible by 2 (even), which is the inverse of the required logic. Option B is wrong because `return n % 2 == 1` works only for positive odd numbers; in Python, the modulo operation with negative numbers can yield -1 instead of 1, making this unreliable for all integers. Option C is wrong because `return not n % 2 == 0` is logically equivalent to `return n % 2 != 0`, thus also returning the inverse of the required result.

322
MCQhard

You are working on a network automation script that reads a configuration file containing firewall rules. Each rule is a dictionary with keys 'source_ip', 'dest_ip', 'action'. The script must iterate over the rules and print all rules where action is 'allow'. However, the script is not printing any output even though there are allow rules in the file. The code snippet is: rules = [{'source_ip':'10.0.0.1','dest_ip':'10.0.0.2','action':'allow'}, {'source_ip':'10.0.0.2','dest_ip':'10.0.0.3','action':'deny'}] for rule in rules: if rule('action') == 'allow': print(rule) What is the most likely cause of the problem?

A.The dictionary does not have an 'action' key
B.The developer used rule['action'] instead of rule.get('action')
C.The for loop syntax is incorrect; it should be for rule in rules:
D.The developer used rule('action') instead of rule['action']
AnswerD

Dictionary access uses square brackets or get method.

Why this answer

In Python, dictionary values are accessed using square brackets (e.g., rule['action']) or the .get() method, not parentheses. Using parentheses like rule('action') attempts to call the dictionary as a function, which raises a TypeError and prevents the script from executing, so no output is printed even though allow rules exist.

Exam trap

The trap here is that candidates may overlook the subtle difference between parentheses and brackets for dictionary access, assuming both work similarly, but Python strictly requires square brackets for key lookup.

How to eliminate wrong answers

Option A is wrong because the dictionary clearly has an 'action' key (as shown in the provided data). Option B is wrong because using rule['action'] is actually the correct way to access a dictionary key; the problem is not about using .get() vs brackets, but about using parentheses instead of brackets. Option C is wrong because the for loop syntax 'for rule in rules:' is correct and not the cause of the issue.

323
MCQeasy

Refer to the exhibit. What is the output?

A.Invalid integer\nSome error
B.No output
C.Some error
D.Invalid integer
AnswerD

The specific ValueError handler runs.

Why this answer

The code attempts to convert the string '12.5' to an integer using int(). Since '12.5' is not a valid integer literal (it contains a decimal point), Python raises a ValueError. The exception is caught by the except clause, which prints 'Invalid integer'.

After the try-except block, there is no further print statement, so the only output is 'Invalid integer'.

Exam trap

Candidates may think that after catching an exception, the program continues to execute code that follows the try-except block, but in this question there is no such code. The trap is recognizing that the output consists solely of the print inside the except.

How to eliminate wrong answers

Option A is wrong because it suggests the output is 'Invalid integer\nSome error' with a literal backslash-n, but the actual output uses real newline characters, not the escape sequence. Option B is wrong because the code does produce output: it prints 'Invalid integer' from the except block and then 'Some error' after the try-except structure. Option C is wrong because the ValueError is caught, so no unhandled error occurs; the program prints both messages and terminates normally.

324
MCQeasy

Which of the following is the correct way to define a function that takes no arguments and returns the value 42?

A.function f(): return 42
B.def f() return 42
C.def f: return 42
D.def f(): return 42
AnswerD

Correct because it uses `def`, parentheses, colon, and the return statement.

Why this answer

The syntax for defining a function in Python requires the def keyword, followed by the function name, parentheses (even if no arguments), a colon, and the indented body. Option B is missing the colon after the parentheses, making it syntactically incorrect.

Exam trap

The trap here is that option B looks almost correct but is missing the mandatory colon. Candidates may overlook the colon and incorrectly select B as well. Only D is valid.

How to eliminate wrong answers

Option A is wrong because Python uses the `def` keyword, not `function`, to define functions. Option B is wrong because it is identical to D but lacks the [CORRECT] marker; however, the question lists D as correct, so B is not the intended answer. Option C is wrong because it omits the parentheses `()` after the function name, which are mandatory even when the function takes no arguments.

325
MCQhard

A developer writes: a = 3; b = 4; c = a + b / 2. What is the value of c?

A.3
B.3.5
C.5
D.5.0
AnswerD

3 + 4/2 = 3 + 2.0 = 5.0.

Why this answer

In Python, the division operator `/` always returns a float, and operator precedence dictates that division is performed before addition. Thus, `b / 2` evaluates to `4 / 2 = 2.0`, then `a + 2.0` yields `3 + 2.0 = 5.0`. Option D is correct because the result is a float value of 5.0.

Exam trap

Python Institute often tests the combination of operator precedence and the fact that `/` always returns a float in Python 3, trapping candidates who expect integer division or who incorrectly group the expression as `(a + b) / 2`.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes integer division or that the expression evaluates to 3, ignoring the division and addition. Option B is wrong because it suggests the result is 3.5, which would occur if the expression were `(a + b) / 2` due to incorrect grouping. Option C is wrong because it gives the integer 5, but Python's `/` operator always returns a float, so the result is 5.0, not the int 5.

326
MCQmedium

A programmer writes: x = 5; y = 2; result = x / y. What is the type of result?

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

True: / operator returns float.

Why this answer

In Python 3, the division operator (/) always returns a floating-point number, even if both operands are integers. Since x and y are both integers (5 and 2), the result of 5 / 2 is 2.5, which is of type float. Therefore, option B is correct.

Exam trap

Python Institute often tests the distinction between Python 3's true division (/) and floor division (//), trapping candidates who assume integer division returns an integer like in Python 2 or other languages such as C or Java.

How to eliminate wrong answers

Option A is wrong because the division operator (/) in Python 3 never returns an int; it always returns a float, even when the division is exact (e.g., 4 / 2 returns 2.0). Option C is wrong because the result of a numeric division is a numeric type, not a string; a string would require explicit conversion or string concatenation. Option D is wrong because complex numbers are created using a literal like 3+4j or the complex() function, not from integer division.

327
Multi-Selecteasy

Which THREE of the following are valid list operations?

Select 3 answers
A.my_list.add(5)
B.my_list.extend([5,6])
C.my_list.push(5)
D.my_list.insert(0,5)
E.my_list.append(5)
AnswersB, D, E

Valid method.

Why this answer

The `extend()` method appends each element of the iterable (here, the list `[5,6]`) to the end of the original list, modifying it in place. This is a valid list operation in Python that adds multiple elements at once.

Exam trap

Python Institute often tests the distinction between list methods and methods from other data structures (like `add()` for sets or `push()` for stacks) to catch candidates who confuse Python's list API with those of other languages or collections.

328
MCQmedium

A Python script uses a dictionary to store user session data. The developer writes `user = {'id': 101, 'name': 'Alice'}` and later tries to access `user['email']`. What is the outcome?

A.It returns an empty string.
B.It raises a KeyError.
C.It returns None.
D.It checks the 'in' operator automatically and returns False.
AnswerB

Accessing a non-existent key directly raises KeyError.

Why this answer

In Python, accessing a dictionary key that does not exist raises a KeyError. The dictionary `user` contains only the keys 'id' and 'name', so `user['email']` triggers a KeyError because the key 'email' is not present. This is a fundamental behavior of Python dictionaries, which do not return default values for missing keys unless a method like `.get()` is used.

Exam trap

Python Institute often tests the distinction between direct bracket access (which raises KeyError) and the `.get()` method (which returns None or a default), tempting candidates to think Python automatically returns a falsy value for missing keys.

How to eliminate wrong answers

Option A is wrong because Python dictionaries never return an empty string for a missing key; they raise a KeyError instead. Option C is wrong because `None` is only returned when using the `.get()` method with no default argument, not with direct bracket access. Option D is wrong because the `in` operator is not automatically invoked when accessing a key; it must be explicitly used to check membership, and even then it returns a boolean, not the value.

329
Multi-Selectmedium

A developer is writing a function that takes a list of numbers and returns the sum of all even numbers. Which two code snippets correctly implement this function? (Select two.)

Select 2 answers
A.def sum_even(nums): return [n for n in nums if n%2==0]
B.def sum_even(nums): total=0; for i in range(len(nums)): if nums[i]%2==0: total+=nums[i]*2; return total
C.def sum_even(nums): total=0; for n in nums: if n%2==0: total+=n; return total
D.def sum_even(nums): total=0; for n in nums: if n%2==1: total+=n; return total
E.def sum_even(nums): return sum(n for n in nums if n%2==0)
AnswersC, E

Correct: loop adds evens to total.

Why this answer

It initializes a total variable to 0, iterates over each number in the list, checks if it is even using the modulo operator (n % 2 == 0), and adds the number to the total. This correctly accumulates the sum of all even numbers and returns the final total.

Exam trap

Python Institute often tests the distinction between returning a filtered list versus returning the sum of filtered values, and the trap here is that candidates may confuse list comprehensions (which produce a list) with generator expressions or accumulator logic that produce a single numeric result.

330
Multi-Selecteasy

Which TWO of the following are valid ways to iterate over a list in reverse order? (Choose two.)

Select 2 answers
A.for item in reversed(lst):
B.for i in range(len(lst)-1, -1, -1):
C.for i in range(len(lst)):
D.for item in lst[-1::-1]:
E.for item in lst:
AnswersA, B

Correct: `reversed(lst)` returns an iterator that yields elements in reverse order without copying the list.

Why this answer

`reversed(lst)` returns an iterator that yields elements in reverse order without modifying the original list. Option B is correct because `range(len(lst)-1, -1, -1)` generates indices from the last to the first, allowing index-based access. These are the two valid methods according to the PCEP certification.

Exam trap

A common trap is thinking that slicing with `[::-1]` is equivalent to `reversed()` for iteration. While both produce reverse order, slicing creates a new list, which may be memory-intensive and is not directly iterating over the original list. The exam often expects you to identify only the methods that iterate over the original list without creating a copy.

331
MCQhard

What is the output of the following code? def test(): try: return 1 finally: return 2 print(test())

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

Correct; finally executes after try's return, and its return value is used.

Why this answer

In Python, a `finally` block always executes, and if both `try` and `finally` contain `return` statements, the `return` in `finally` overrides the one in `try`. The function `test()` returns 2, not 1, because the `finally` block's return value is the one that is actually used.

Exam trap

The PCEP exam often tests the misconception that a `try` block's return will take precedence over a `finally` block's return, leading candidates to pick option D (1) instead of understanding that `finally` overrides the return value.

How to eliminate wrong answers

Option A is wrong because the function does return a value (2), not None. Option B is wrong because no error occurs; the `finally` block executes cleanly and returns a value. Option D is wrong because although `return 1` is executed in the `try` block, the `finally` block's `return 2` overrides it, so the function returns 2, not 1.

332
MCQhard

A developer needs to convert a string '25' to an integer and then add 10. Which code correctly performs this?

A.print(int('25') + 10)
B.print('25' + 10)
C.print(int('25') + '10')
D.print('25' + str(10))
AnswerA

Correct conversion and addition.

Why this answer

`int('25')` converts the string '25' to the integer 25, and then `+ 10` performs integer addition, resulting in 35. The `print()` function outputs the result. This follows Python's type conversion rules where explicit conversion is required to combine a string and an integer in arithmetic.

Exam trap

Python Institute often tests the misconception that Python will automatically convert types in arithmetic expressions, leading candidates to choose options that mix strings and integers without explicit conversion.

How to eliminate wrong answers

Option B is wrong because it attempts to add a string ('25') and an integer (10) directly, which raises a TypeError in Python as the `+` operator is not defined for mixed string-integer operands. Option C is wrong because it adds an integer (from `int('25')`) to a string ('10'), which also raises a TypeError for the same reason. Option D is wrong because it concatenates the string '25' with the string '10' (from `str(10)`), producing '2510' rather than performing arithmetic addition.

333
MCQeasy

What function is used to read input from the user in Python 3?

A.read_input()
B.sys.stdin.readline()
C.input()
D.raw_input()
AnswerC

Standard for user input.

Why this answer

In Python 3, the built-in `input()` function reads a line from standard input and returns it as a string. This is the standard and simplest way to capture user input, replacing the Python 2 `raw_input()` function.

Exam trap

The PCEP exam often tests the distinction between Python 2 and Python 3 input functions, trapping candidates who remember `raw_input()` from Python 2 or who think `sys.stdin.readline()` is the standard way to read user input.

How to eliminate wrong answers

Option A is wrong because `read_input()` is not a built-in Python function; it does not exist in the standard library. Option B is wrong because `sys.stdin.readline()` is a valid method to read input from standard input, but it is not the primary or simplest function for general user input; it requires importing the `sys` module and returns the newline character at the end unless stripped. Option D is wrong because `raw_input()` was the input function in Python 2, but it was removed in Python 3; using it in Python 3 raises a `NameError`.

334
MCQmedium

A team is building a configuration parser that reads a file containing key=value pairs. They use a dictionary to store the configuration. The parser function `load_config(filename)` opens the file, reads line by line, splits on '=', and populates a dictionary. Some lines have comments starting with '#'. The developer wants to ensure that the dictionary is not polluted with comment lines. They write: `if line.startswith('#'): continue`. However, after parsing, the dictionary contains an entry with key '#' because some lines have no '=' sign. For example, a line like `#comment` is being added as a key with value None. The developer wants to fix this. Which modification should be made?

A.Use `key, value = line.split('=', 1)` and catch ValueError if less than two parts.
B.Strip the line of whitespace before checking for comments.
C.Check `if '=' not in line: continue` before splitting.
D.Replace `startswith('#')` with `line.lstrip().startswith('#')` and also skip empty lines.
AnswerC

Explicitly skip lines without '='.

Why this answer

The core issue is that lines without an '=' sign (like `#comment`) are still processed by the split, causing the entire line to become a key with no value. By explicitly checking `if '=' not in line: continue` before splitting, the developer ensures that only lines containing a key-value separator are added to the dictionary, effectively filtering out comment lines and any other malformed lines.

Exam trap

Python Institute often tests the misconception that checking for a comment marker alone is sufficient, when the real issue is that any line without an '=' sign (including comments) will be incorrectly parsed as a key with no value.

How to eliminate wrong answers

Option A is wrong because catching a ValueError from `split('=', 1)` would still attempt to split a line like `#comment`, which has no '=', raising the exception; while this would skip the line, it is less explicit and less efficient than checking for '=' beforehand. Option B is wrong because stripping whitespace before checking for comments does not address the root problem: lines without '=' (including comments) will still be split and added to the dictionary. Option D is wrong because while `line.lstrip().startswith('#')` correctly identifies comment lines even with leading whitespace, it does not handle lines that have no '=' sign; such lines would still be processed and added as dictionary entries.

335
MCQmedium

Refer to the exhibit. What is the final value of my_list?

A.[1, 2, 3, 4, 5]
B.[1, 4, 9, 16, 25]
C.[1, 8, 27, 64, 125]
D.[1, 4, 27, 16, 125]
AnswerD

Even numbers (2,4) are squared, odd numbers (1,3,5) are cubed.

Why this answer

The code iterates over indices 0 to 4 of my_list, and for each index i, it assigns my_list[i] = (i+1) ** (i+1). This computes 1^1, 2^2, 3^3, 4^4, 5^5, resulting in [1, 4, 27, 16, 125]. Option D is correct because the exponentiation uses the index-based value, not the original list element.

Exam trap

The trap here is that candidates often assume the exponent is fixed (e.g., 2 or 3) rather than recognizing that the exponent changes with each iteration, leading them to pick the squaring or cubing options.

How to eliminate wrong answers

Option A is wrong because it assumes the list remains unchanged, ignoring the loop that modifies each element. Option B is wrong because it incorrectly applies squaring (i+1)**2 instead of exponentiation with the exponent equal to the base (i+1)**(i+1). Option C is wrong because it mistakenly cubes each element (i+1)**3, which would give [1, 8, 27, 64, 125] but the code uses the index as both base and exponent.

336
MCQeasy

A student tries to write a program that prints the square of a number. The code: num = 5 print("The square is " + num ** 2) When run, a TypeError occurs. Which of the following fixes the error and produces exactly the output 'The square is 25'?

A.Change to: print("The square is " + str(num ** 2))
B.Change to: print("The square is " + num ** 2)
C.Change to: print("The square is", num ** 2)
D.Change to: print("The square is " + (num ** 2))
AnswerA

str() converts the integer to string for concatenation.

Why this answer

It converts the integer result of `num ** 2` (which is 25) to a string using `str()`, allowing concatenation with the string literal `"The square is "`. Without this conversion, Python raises a `TypeError` because the `+` operator cannot concatenate a string and an integer directly.

Exam trap

Python Institute often tests the distinction between concatenation with `+` (which requires matching types) and the `print()` function's multiple arguments with commas (which automatically adds a space separator but does not require type conversion), leading candidates to mistakenly choose Option C when the exact output string must match.

How to eliminate wrong answers

Option B is wrong because it is identical to the original erroneous code — it still tries to concatenate a string with an integer, causing a `TypeError`. Option C is wrong because although it runs without error and prints `The square is 25`, it uses a comma separator which inserts a space automatically, producing `The square is 25` (with a space before the number) — but the question requires exactly the output `'The square is 25'` (no extra space before 25), so it does not match. Option D is wrong because wrapping `num ** 2` in parentheses does not change its type; it remains an integer, so the `TypeError` persists.

337
Multi-Selecthard

Given the following code, which of the following statements are true after execution? (Choose three.) x = 10 y = 3.0 z = x / y w = x // y

Select 3 answers
A.The expression x % y is valid.
B.The value of z is approximately 3.33 (type float).
C.The type of w is int.
D.The expression x / y returns an integer.
E.The value of w is 3.0.
AnswersA, B, E

Modulo works with floats.

Why this answer

The modulo operator % works with both integers and floats in Python. Here, x is an int and y is a float, so x % y is valid and returns a float result (the remainder of the division).

Exam trap

The PCEP exam often tests the misconception that floor division (//) returns an int when one operand is a float, or that true division (/) can return an integer, leading candidates to incorrectly select options C or D.

338
MCQhard

Refer to the exhibit. Why does the code successfully remove all even numbers but the output is [1, 3, 5]?

A.Because the condition checks for even numbers and removes them correctly without side effects.
B.Because removing elements while iterating forward causes skipping of elements, but in this case the even numbers are at indices 0,2,4 and the removal shifts subsequent elements; however, the loop variable i increments and skips the next odd number, leading to correct removal by chance.
C.Because the range is computed once and the list is shortened, so the loop ends early.
D.Because the remove() method removes only the first occurrence, and the loop iterates backwards.
AnswerB

The code works because the even numbers are at even indices and after removal, the next element becomes at the same index, but since i increments, it skips the next element; however, the skipped elements are odd and remain, so the result is all odds.

Why this answer

When iterating forward over a list while removing elements, the removal shifts subsequent elements to lower indices, causing the loop variable i to skip the next element. In this specific case, the even numbers happen to be at indices 0, 2, and 4, and after each removal the next element (which is odd) shifts into the current index, but i increments past it, so the odd numbers are never checked and remain, resulting in the correct output by coincidence rather than by correct logic.

Exam trap

The PCEP exam often tests the subtle bug of modifying a list while iterating forward, where candidates mistakenly believe the code works correctly because the output happens to be correct in this specific case, overlooking that the logic is flawed and would fail with a different arrangement of numbers.

How to eliminate wrong answers

Option A is wrong because the condition does not remove even numbers without side effects; removing elements while iterating forward causes skipping of elements, which is a side effect that can lead to incorrect results in other scenarios. Option C is wrong because the range is computed once at the start of the loop, but the list is shortened during iteration, which causes the loop to potentially access indices beyond the new list length, but in this case the loop ends early because the range length is based on the original list, not because of early termination. Option D is wrong because the remove() method removes the first occurrence of the value, not by index, and the loop iterates forward, not backward; iterating backward would avoid the skipping issue.

339
Drag & Dropmedium

Order the steps to define a class and create an object 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

In Python, to define a class and create an object, you must first write a class definition using the `class` keyword, which typically includes the `__init__` method (the constructor) to initialize attributes. After that, you instantiate the class by calling it like a function, optionally passing arguments to `__init__`. Finally, you use the resulting object by accessing its attributes or calling its methods.

Any deviation from this order, such as instantiating before defining the class or omitting the constructor, will lead to errors because the class must exist and be properly defined before any objects can be created.

340
MCQmedium

A program needs to read a user's age and print a message if they are 18 or older. Which code snippet correctly accomplishes this?

A.age = int(input('Age: ')) if age >= '18': print('Adult')
B.age = int(input('Age: ')) if age >= 18: print('Adult')
C.age = input('Age: ') if age >= 18: print('Adult')
D.age = input('Age: ') if age == 18: print('Adult')
AnswerB

Correct conversion and comparison.

Why this answer

It uses `int()` to convert the user input to an integer, then compares it with the integer `18` using the `>=` operator. This ensures a proper numeric comparison, and if the condition is true, it prints 'Adult'.

Exam trap

Python Institute often tests the distinction between string and integer types, and the trap here is that candidates forget to convert the input to an integer, leading to a type mismatch error when using comparison operators like `>=`.

How to eliminate wrong answers

Option A is wrong because it compares an integer (`age`) with a string `'18'`, which in Python 3 raises a `TypeError` (or in some contexts may produce unexpected results). Option C is wrong because `input()` returns a string, and comparing a string to the integer `18` with `>=` raises a `TypeError` (strings and integers cannot be compared with relational operators). Option D is wrong because it uses `==` instead of `>=`, so it only prints 'Adult' when the age is exactly 18, not for ages greater than 18, and also compares a string (from `input()`) to an integer, which would raise a `TypeError`.

341
Multi-Selectmedium

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

Select 2 answers
A.for
B.var123
C.my-var
D.1var
E._myVar
AnswersB, E

Valid: letters and digits.

Why this answer

(var123) is correct because Python variable names must start with a letter or underscore, and can contain letters, digits, or underscores. 'var123' starts with a letter and contains only valid characters, making it a legal identifier.

Exam trap

Python Institute often tests the rule that hyphens are not allowed in variable names, tricking candidates who are used to hyphenated names from other languages like HTML or CSS.

342
MCQmedium

A junior developer writes: x = 10; y = 3; print(x % y). What will be printed?

A.3.33
B.1
C.0
D.3
AnswerB

Remainder when 10 is divided by 3.

Why this answer

The modulo operator (%) returns the remainder of the division of the left operand by the right operand. Here, 10 divided by 3 equals 3 with a remainder of 1, so print(x % y) outputs 1.

Exam trap

Python Institute often tests the distinction between the modulo operator (%) and integer division (//) or floating-point division (/), trapping candidates who confuse remainder with quotient or decimal result.

How to eliminate wrong answers

Option A is wrong because 3.33 would be the result of floating-point division (10 / 3), not the modulo operation. Option C is wrong because 0 would only occur if the division had no remainder (e.g., 9 % 3). Option D is wrong because 3 is the quotient of integer division (10 // 3), not the remainder from modulo.

343
MCQeasy

Which of the following statements about Python indentation is true?

A.Indentation is optional but recommended.
B.You can mix tabs and spaces freely.
C.Indentation must be consistent within a block.
D.Indentation only matters for loops and conditionals.
AnswerC

Correct.

Why this answer

Python enforces consistent indentation within a block to define the scope of statements. Unlike many languages that use braces, Python relies on the indentation level to group statements, and any inconsistency (e.g., mixing spaces and tabs or varying the number of spaces) will raise an IndentationError.

Exam trap

The trap here is that candidates often think indentation is merely a style recommendation (like in other languages) or that it only applies to control flow statements, but Python strictly enforces it for all block structures, and mixing tabs with spaces is a common pitfall that leads to runtime errors.

How to eliminate wrong answers

Option A is wrong because indentation is not optional in Python; it is syntactically mandatory to define code blocks, and omitting it will cause a syntax error. Option B is wrong because mixing tabs and spaces is not allowed; Python 3 disallows this and will raise a TabError due to ambiguity in indentation levels. Option D is wrong because indentation matters for all compound statements, including function definitions, class definitions, try/except blocks, and with statements, not just loops and conditionals.

344
MCQmedium

A function returns a tuple. Which code correctly unpacks the tuple? def min_max(numbers): return min(numbers), max(numbers) result = min_max([3, 1, 2])

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

Correct: Parenthesized target list unpacks the tuple into a and b.

Why this answer

Both options B and C correctly unpack the tuple. Option B uses explicit parentheses, while option C uses the implicit form — both are valid tuple unpacking syntax in Python. Option A unpacks via indexing (not tuple unpacking), and option D incorrectly swaps the values.

Exam trap

Candidates may think only one syntactic form is correct, but assignment target lists can be parenthesized or bare; both perform tuple unpacking.

How to eliminate wrong answers

Option D is wrong because it swaps the values: `a = result[1]` assigns the maximum to `a` and `b = result[0]` assigns the minimum to `b`, which does not correctly unpack the tuple as returned by the function (min, max).

345
MCQhard

Given 's = "Hello"; t = s[0:3]; print(t)', what is the output?

A.ello
B.H
C.Hell
D.Hel
AnswerD

s[0:3] gives first three characters.

Why this answer

String slicing in Python uses the syntax `s[start:stop]`, where the stop index is exclusive. For `s = "Hello"`, `s[0:3]` extracts characters from index 0 up to but not including index 3, resulting in indices 0 ('H'), 1 ('e'), and 2 ('l'), giving the substring "Hel".

Exam trap

The trap here is that candidates often confuse the exclusive stop index with an inclusive one, leading them to select "Hell" (option C) because they mistakenly include index 3, or they misremember the starting index and pick "ello" (option A).

How to eliminate wrong answers

Option A is wrong because it represents `s[1:5]` (or `s[1:]`), which would skip the first character, not the slice `s[0:3]`. Option B is wrong because it represents `s[0:1]`, which extracts only the first character, not the first three. Option C is wrong because it represents `s[0:4]`, which includes index 3 ('l') and would output "Hell", but the correct slice stops at index 3 (exclusive), so only "Hel" is produced.

346
MCQhard

Given the code: my_list = [1, 2, 3, 4, 5]. What is the output of print(my_list[-3:-1])?

A.[4, 5]
B.[3, 4]
C.[2, 3]
D.[3, 4, 5]
AnswerB

Negative indices: -3 corresponds to index 2 (value 3), -1 corresponds to index 4 (value 5) but stop exclusive, so indices 2 and 3: [3,4].

Why this answer

Python list slicing with negative indices counts from the end of the list. my_list[-3:-1] starts at index -3 (value 3) and goes up to but does not include index -1 (value 5), so it returns [3, 4].

Exam trap

The trap here is that candidates often forget that the end index in a slice is exclusive, causing them to include the element at index -1 and choose option D instead of B.

How to eliminate wrong answers

Option A is wrong because it assumes the slice includes the end index, returning [4, 5] which would be my_list[-2:]. Option C is wrong because it returns [2, 3], which would be the result of my_list[-4:-2] or my_list[1:3]. Option D is wrong because it includes the element at index -1, but Python slicing excludes the end index, so [3, 4, 5] would be my_list[-3:].

347
MCQhard

A developer writes the following code snippet: for i in range(3): for j in range(2): if i == j: break else: print(i, 'outer') What is the output?

A.0 outer\n2 outer
B.2 outer
C.0 outer\n1 outer\n2 outer
D.No output
AnswerB

Only when i=2 does the inner loop complete without break.

Why this answer

The code uses nested loops with a `for-else` construct. The `else` block executes only if the inner loop completes without a `break`. When `i == j`, the `break` exits the inner loop, skipping the `else`.

For `i=0`, `j=0` triggers `break`; for `i=1`, `j=1` triggers `break`; for `i=2`, the inner loop runs `j=0,1` without any `i==j` (since 2 != 0 and 2 != 1), so the `else` executes, printing `2 outer`. Thus, only option B is correct.

Exam trap

Python Institute often tests the `for-else` behavior in nested loops, and the trap here is that candidates mistakenly think the `else` runs after every outer iteration or that `break` only exits the outer loop, when in fact `break` only exits the innermost loop and the `else` is tied to that inner loop's completion status.

How to eliminate wrong answers

Option A is wrong because it incorrectly includes `0 outer`; when `i=0`, the inner loop breaks at `j=0` (since `i==j`), so the `else` does not execute. Option C is wrong because it claims all three values print; only `i=2` avoids the break condition, so `0 outer` and `1 outer` are never printed. Option D is wrong because there is output: the `else` block prints `2 outer` when `i=2`.

348
MCQhard

In a try-except block, a developer has two except clauses: except ValueError: and except: (bare except). If the code in the try block raises a ValueError, which except clause is executed?

A.Both in order
B.Neither; program crashes
C.The ValueError except clause
D.The bare except clause
AnswerC

Correct: The specific exception handler is matched first.

Why this answer

When a ValueError is raised in the try block, Python searches the except clauses in the order they appear. It finds the first matching clause, which is `except ValueError:`, and executes it. The bare `except:` clause is only reached if no preceding named except clause matches the exception type.

Exam trap

The PCEP exam often tests the order of except clauses and the fact that Python executes only the first matching handler, leading candidates to mistakenly think both clauses run or that the bare except overrides a specific match.

How to eliminate wrong answers

Option A is wrong because Python executes only the first matching except clause, not both; after handling the ValueError, control passes to the code after the try-except block. Option B is wrong because the ValueError is explicitly caught by the `except ValueError:` clause, so the program does not crash. Option D is wrong because the bare `except:` clause is a catch-all that only runs if no earlier except clause matches the exception; since ValueError matches the first clause, the bare except is skipped.

349
MCQmedium

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

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

Correct. The loop iterates from 1 to 5, skipping 3 due to continue, resulting in 1,2,4,5.

Why this answer

The code uses a for loop with range(1,6) to iterate over numbers 1 through 5. Inside the loop, an if statement checks if the current number equals 3; if true, the continue statement skips the print(i) for that iteration. Thus, when i is 3, the print is skipped, so the output is '1 2 4 5'.

Option B is correct because it matches this output.

Exam trap

Candidates often confuse range(1,6) with range(5) or miss that continue skips only the current iteration, not the whole loop. They may also forget that range start is inclusive and end is exclusive.

How to eliminate wrong answers

Option A is wrong because it includes 0, but the loop starts at 0 and prints it before the continue condition is met, so 0 should be printed; however, the correct output includes 0, so Option A is actually correct? Wait, let me re-evaluate: The loop range(5) produces 0,1,2,3,4. When i==3, continue skips print(i), so printed values are 0,1,2,4. Option A says '0 1 2 4 5' which includes 5, but range(5) stops at 4, so 5 is never generated.

Option A is wrong because it incorrectly includes 5. Option C is wrong because it includes 3, but the continue statement skips printing when i==3, so 3 should not appear. Option D is wrong because it omits 0 and 1, but the loop prints 0 and 1 before the continue condition is encountered.

350
MCQeasy

A developer writes a script to read user input using input() and then prints it. However, the program crashes when the user enters a number. What is the most likely cause?

A.The input is read as a string, but the code treats it as a number without conversion.
B.The script uses Python 2, where input() evaluates input as code.
C.The print() function expects a string, but the input is a number.
D.The input() function cannot handle numeric input.
AnswerA

Correct: input() returns a string, so numeric operations fail.

Why this answer

The `input()` function in Python 3 always returns a string, regardless of what the user types. If the user enters a number, the program may crash if the code later performs an operation (like arithmetic or comparison) on that string without first converting it to an integer or float using `int()` or `float()`. This mismatch between the string type and the expected numeric type causes a `TypeError`.

Exam trap

Python Institute often tests the misconception that `input()` can return different types based on the input, when in Python 3 it always returns a string, leading candidates to overlook the need for explicit conversion.

How to eliminate wrong answers

Option B is wrong because in Python 2, `input()` evaluates the input as Python code, which could cause crashes with numeric input, but the question context (PCEP exam) assumes Python 3, where `input()` returns a string. Option C is wrong because `print()` can handle any data type, including numbers, by converting them to strings automatically. Option D is wrong because `input()` can handle numeric input perfectly fine; it just stores it as a string, which is not a crash in itself.

351
MCQeasy

A junior developer writes a Python script to calculate the average of three numbers: avg = a + b + c / 3. What is the problem with this code?

A.Division by a variable is not allowed
B.Missing parentheses cause incorrect order of operations
C.Python cannot divide integers
D.Variable names are too short
AnswerB

Division has higher precedence than addition, so parentheses are needed to group the sum.

Why this answer

Python follows the standard mathematical order of operations (PEMDAS/BODMAS), where division has higher precedence than addition. The expression `a + b + c / 3` is evaluated as `a + b + (c / 3)`, which calculates the average incorrectly. To compute the correct average, parentheses must be used: `(a + b + c) / 3`.

Exam trap

The PCEP exam often tests the misconception that Python evaluates expressions strictly left-to-right, leading candidates to think `a + b + c / 3` works correctly, when in fact operator precedence overrides left-to-right evaluation.

How to eliminate wrong answers

Option A is wrong because Python fully supports division by a variable; there is no restriction on using variables as divisors. Option C is wrong because Python can divide integers using the `/` operator, which returns a float result (true division) in Python 3. Option D is wrong while short variable names are not a best practice, they are syntactically valid and do not cause incorrect calculation results.

352
MCQhard

A developer wants to generate a list of squares of integers from 1 to 10 inclusive. Which list comprehension is correct?

A.[x**2 for x in range(11)]
B.[x**2 for x in range(10)]
C.[x**2 for x in range(1, 10)]
D.[x**2 for x in range(1, 11)]
AnswerD

Correctly generates squares for 1 through 10.

Why this answer

`range(1, 11)` generates integers from 1 to 10 inclusive, and the list comprehension `[x**2 for x in range(1, 11)]` squares each integer, producing the desired list of squares. The `range()` function's stop value is exclusive, so `range(1, 11)` stops at 10, covering all numbers from 1 to 10.

Exam trap

Python Institute often tests the exclusive nature of the `stop` argument in `range()`, trapping candidates who forget that `range(10)` stops at 9 and `range(1, 10)` stops at 9, leading them to choose options that omit the final value (10) or include an unwanted starting value (0).

How to eliminate wrong answers

Option A is wrong because `range(11)` generates integers from 0 to 10 inclusive, including 0, which is not in the required range (1 to 10). Option B is wrong because `range(10)` generates integers from 0 to 9, missing 10 and including 0. Option C is wrong because `range(1, 10)` generates integers from 1 to 9, missing 10.

353
MCQmedium

A developer wants to extract the file extension from a filename: 'report.pdf'. Which string method will return 'pdf'?

A.'report.pdf'.replace('.', '')
B.'report.pdf'.split('.')[-1]
C.'report.pdf'.split('.')[1]
D.'report.pdf'.removeprefix('report.')
AnswerB

Returns 'pdf'.

Why this answer

The `split('.')` method divides the string at each period, returning a list `['report', 'pdf']`. Accessing index `-1` retrieves the last element, which is the file extension `'pdf'`. This is a common Python idiom for extracting file extensions.

Exam trap

The trap here is that candidates may choose option C because it works for simple cases like `'report.pdf'`, but The PCEP exam often tests the edge case of filenames with multiple dots to catch those who do not use `[-1]` for the last element.

How to eliminate wrong answers

Option A is wrong because `replace('.', '')` removes all periods from the string, resulting in `'reportpdf'`, not the extension. Option C is wrong because `split('.')[1]` would work for this specific filename but fails for filenames with multiple dots (e.g., `'my.file.txt'` returns `'file'` instead of `'txt'`), making it less robust than using `[-1]`. Option D is wrong because `removeprefix('report.')` only removes the exact prefix `'report.'` and would fail for any other filename, returning the original string unchanged if the prefix does not match.

354
MCQmedium

A programmer writes the following code: if x > 5: print('Greater') What is the most likely cause of an IndentationError?

A.The print statement is not indented.
B.The comparison operator is wrong.
C.The variable x is undefined.
D.The colon after the condition is missing.
AnswerA

Requires indentation.

Why this answer

In Python, the colon at the end of an if statement signals the start of an indented block. The print statement must be indented (typically 4 spaces) to be part of that block. Without indentation, Python raises an IndentationError because it expects a suite of statements under the if clause.

Exam trap

The PCEP exam often tests that candidates understand IndentationError is a syntax-level error caused by incorrect spacing, not by missing colons or undefined variables, which produce different error types.

How to eliminate wrong answers

Option B is wrong because the comparison operator '>' is valid and correct for checking if x is greater than 5; an IndentationError is unrelated to operator choice. Option C is wrong because an undefined variable would cause a NameError, not an IndentationError. Option D is wrong because the colon is present in the code; if it were missing, a SyntaxError would occur, not an IndentationError.

355
Multi-Selecthard

Which TWO statements correctly describe Python's dynamic typing?

Select 2 answers
A.Variable types must be declared before use.
B.Python checks types only at compile time.
C.A variable's type is fixed once assigned.
D.The interpreter infers the type from the assigned value.
E.The type of a variable can change at runtime.
AnswersD, E

The type is determined by the object assigned to the variable.

Why this answer

Python's dynamic typing means the interpreter determines the type of a variable at runtime based on the value assigned to it. You do not need to declare the type explicitly; the type is inferred from the object the variable references.

Exam trap

The PCEP exam often tests the misconception that dynamic typing means a variable's type is fixed after first assignment, or that type checking happens at compile time, leading candidates to incorrectly select Option C or B.

356
Multi-Selecthard

Which THREE of the following are valid ways to iterate over a list?

Select 3 answers
A.for i in mylist:
B.i = 0 while i < len(mylist): print(mylist[i]) i += 1
C.foreach i in mylist:
D.iter(mylist)
E.for i in range(len(mylist)):
AnswersA, B, E

Direct iteration over elements.

Why this answer

Python's `for i in mylist:` syntax directly iterates over each element of the list `mylist`, assigning the element value to the loop variable `i` in each iteration. This is the standard and most Pythonic way to traverse a list.

Exam trap

Python Institute often tests the distinction between creating an iterator with `iter()` and actually iterating over it, leading candidates to mistakenly think `iter(mylist)` alone is a loop construct.

357
MCQmedium

A programmer needs to store configuration settings keyed by string, where each key maps to a list of allowed values. Which data structure is most appropriate?

A.A tuple of lists where each list starts with the key.
B.A dictionary where keys are strings and values are lists.
C.A list of tuples where each tuple contains a key and a list of values.
D.A set of strings representing the keys, with a separate list for values.
AnswerB

Provides O(1) average key lookup and each key maps to a list of allowed values.

Why this answer

A dictionary in Python provides direct key-to-value mapping, making it ideal for storing configuration settings where each string key must map to a list of allowed values. Dictionaries offer O(1) average-time complexity for lookups, which is efficient for retrieving the list of values for a given key. This structure directly models the requirement without unnecessary nesting or indirection.

Exam trap

Python Institute often tests the distinction between data structures that store pairs (like dictionaries) versus those that store sequences (like lists or tuples), and the trap here is that candidates may choose a list of tuples (Option C) because it visually pairs keys and values, but overlook that it lacks the efficient key-based lookup that a dictionary provides.

How to eliminate wrong answers

Option A is wrong because a tuple of lists where each list starts with the key is not a native Python data structure for keyed access; it would require linear scanning to find a key, which is inefficient and error-prone. Option C is wrong because a list of tuples, while able to store key-value pairs, does not provide direct key-based lookup and would require O(n) search time, defeating the purpose of a configuration store. Option D is wrong because using a set of strings for keys with a separate list for values fails to associate each key with its specific list of values, making it impossible to retrieve the correct list for a given key without additional logic.

358
Multi-Selecteasy

Which THREE of the following are Python data types?

Select 3 answers
A.str
B.math
C.bool
D.float
E.None
AnswersA, C, D

String is a data type.

Why this answer

`str` is a built-in Python data type used to represent sequences of characters, i.e., strings. In Python, strings are immutable and are defined by enclosing text in single, double, or triple quotes.

Exam trap

The PCEP exam often tests the distinction between a data type and a module or a value, so candidates may mistakenly select `math` (a module) or `None` (a value) as data types because they appear frequently in Python code.

359
MCQmedium

Which data type is most appropriate to store a user's age in a Python program?

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

Correct. Age is a whole number.

Why this answer

A user's age is a whole number without a fractional component, so the integer type (int) is the most appropriate choice. Python's int can represent any integer value, including ages like 25 or 0, without the overhead or precision issues of floating-point numbers.

Exam trap

Python Institute often tests the distinction between numeric types by presenting a scenario where a float seems plausible (e.g., 'age could be 25.5 years'), but the PCEP expects you to recognize that age is conventionally an integer and that Python's int is the correct choice for whole-number data.

How to eliminate wrong answers

Option B (float) is wrong because age is always a whole number; using float would introduce unnecessary decimal precision and potential rounding errors, such as representing 25 as 25.0. Option C (bool) is wrong because a boolean can only store True or False (1 or 0), which cannot represent the full range of possible ages. Option D (str) is wrong because while a string could store an age like '25', it would prevent arithmetic operations (e.g., age + 1) and is semantically incorrect for a numeric value.

360
MCQhard

Which of the following expressions will evaluate to True?

A.3 == 3.0
B.2 + 2 * 2 == 8
C.10 / 3 == 3
D.'a' > 'b'
AnswerA

True, numeric comparison converts 3.0 to 3.

Why this answer

Python's `==` operator performs value equality comparison, and the integer `3` and the float `3.0` represent the same numeric value. Python automatically converts the integer to a float for comparison, so `3 == 3.0` evaluates to `True`.

Exam trap

Python Institute often tests the misconception that `==` requires identical data types, leading candidates to think `3 == 3.0` is `False`, or that operator precedence is left-to-right without considering multiplication before addition.

How to eliminate wrong answers

Option B is wrong because operator precedence in Python dictates that multiplication (`*`) is evaluated before addition (`+`), so `2 + 2 * 2` equals `2 + 4 = 6`, not `8`, making `6 == 8` evaluate to `False`. Option C is wrong because the division operator `/` in Python 3 always returns a float, and `10 / 3` yields `3.3333333333333335`, which is not equal to the integer `3`, so `10 / 3 == 3` is `False`. Option D is wrong because string comparison in Python uses lexicographic order based on ASCII/Unicode code points; the character `'a'` has a Unicode code point of 97, while `'b'` has 98, so `'a' > 'b'` evaluates to `False`.

361
MCQmedium

A program calculates the total price including tax: total = price * 1.08. The variable price is assigned as price = 100.0. After execution, total is 108.0. The developer then changes price to 100. What will total be?

A.The program will raise a TypeError
B.It depends on the Python version
C.108.0
D.108
AnswerC

Correct: float * int yields float.

Why this answer

In Python, multiplying an integer (100) by a float (1.08) results in a float (108.0). The expression `price * 1.08` performs implicit type coercion to float, so even when `price` is changed from 100.0 to 100, the result remains 108.0, not 108.

Exam trap

Python Institute often tests the misconception that changing an integer literal to a float literal changes the result type, when in fact the result type is determined by the wider operand (the float 1.08) regardless of whether price is 100 or 100.0.

How to eliminate wrong answers

Option A is wrong because Python does not raise a TypeError when multiplying an int by a float; it performs implicit type conversion and returns a float. Option B is wrong because the behavior of mixed-type arithmetic is consistent across all Python 3 versions—int * float always yields a float. Option D is wrong because the result is 108.0 (a float), not 108 (an int), due to the presence of the float literal 1.08 in the multiplication.

362
Multi-Selecthard

Which TWO of the following code snippets will produce the output '0 1 2'? (Choose two.)

Select 2 answers
A.for i in range(5): if i%2==0: print(i); else: continue
B.i=0; while i<3: print(i); i+=1; else: print('done')
C.for i in range(5): if i>2: break; print(i)
D.for i in range(3): print(i)
E.i=0; while i<3: print(i)
AnswersC, D

Correct: prints 0,1,2 then breaks.

Why this answer

The loop iterates over range(5) (0,1,2,3,4), but the break statement executes when i > 2, so the loop terminates after printing 0, 1, and 2. Option D is correct because range(3) generates exactly the sequence 0, 1, 2, and each value is printed in order.

Exam trap

Python Institute often tests the distinction between a for loop with range() and a while loop that requires an explicit increment; the trap here is that Option E looks like it should work but omits the increment, leading to an infinite loop, which candidates may overlook if they mentally add the missing i+=1.

363
MCQeasy

A junior developer writes: result = input("Enter first: ") + input("Enter second: ") and then prints result. When entering 5 and 3, the output is '53'. Which explanation is correct?

A.The code uses the wrong operator; it should use the & operator for addition.
B.The input() function automatically selects the correct type, but the + operator is overloaded to concatenate.
C.Python automatically converts strings to numbers when using +, but only for integers.
D.The input() function returns a string, so + performs string concatenation.
AnswerD

input() always returns a string, so + concatenates.

Why this answer

The `input()` function in Python always returns a string, regardless of what the user types. When the `+` operator is used with two strings, it performs concatenation, not arithmetic addition. Thus, entering 5 and 3 results in the strings '5' and '3' being joined to produce '53'.

Exam trap

The trap here is that candidates may assume `input()` returns a numeric type when numbers are entered, or that Python's dynamic typing will automatically convert strings to numbers for addition, leading them to choose option B or C instead of recognizing the default string behavior.

How to eliminate wrong answers

Option A is wrong because the `&` operator is a bitwise AND operator in Python, not an arithmetic addition operator; using it would produce a different, incorrect result. Option B is wrong because `input()` does not automatically select the correct type; it always returns a string, and the `+` operator is overloaded to concatenate strings, but that is not an automatic type selection. Option C is wrong because Python does not automatically convert strings to numbers when using `+`; attempting to add a string and a number with `+` raises a TypeError, and the statement about 'only for integers' is false.

364
Multi-Selectmedium

Which TWO statements about Python lists are true?

Select 2 answers
A.Lists preserve the order of elements.
B.Lists have a fixed size once created.
C.Lists can be modified after creation.
D.Lists are immutable.
E.All elements in a list must be of the same type.
AnswersA, C

Lists are ordered.

Why this answer

Python lists are ordered collections that maintain the insertion order of elements. This means the sequence in which items are added is preserved, and you can access them by their index positions.

Exam trap

Python Institute often tests the misconception that lists are immutable or fixed-size, confusing them with tuples or arrays in other languages, and also tests the false assumption that all elements must be of the same type.

365
MCQmedium

What is the output of the code in the exhibit?

A.TypeError
B.'105'
C.105
D.15
AnswerA

Cannot concatenate str and int.

Why this answer

The code attempts to concatenate a string ('10') and an integer (5) using the + operator. In Python, the + operator does not implicitly convert types; it raises a TypeError because it cannot determine whether to perform string concatenation or integer addition. This is a fundamental rule of Python's strong typing system.

Exam trap

Python Institute often tests the misconception that Python will automatically convert types (like JavaScript or PHP do), leading candidates to expect either concatenation or addition instead of recognizing that Python raises a TypeError for incompatible operand types.

How to eliminate wrong answers

Option B is wrong because it assumes Python would implicitly convert the integer 5 to a string and concatenate, producing '105', but Python raises a TypeError instead of performing implicit type coercion. Option C is wrong because it assumes Python would implicitly convert the string '10' to an integer and add, producing 105, but Python does not allow implicit conversion of strings to integers in this context. Option D is wrong because it assumes the string '10' is treated as the integer 10 and added to 5 to get 15, but Python does not perform implicit type conversion for the + operator between a string and an integer.

366
MCQmedium

Refer to the exhibit. If the user enters 5 and 3, what is the output?

A.8
B.5 3
C.TypeError
D.53
AnswerD

String concatenation of '5' and '3'.

Why this answer

In Python, the `input()` function always returns a string. When the user enters 5 and 3, the `+` operator concatenates the two strings '5' and '3', producing the string '53'. Option D is correct because no numeric conversion is performed.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type when digits are entered, leading candidates to expect arithmetic addition instead of string concatenation.

How to eliminate wrong answers

Option A is wrong because it assumes the inputs are automatically converted to integers and added, but `input()` returns strings and no `int()` conversion is applied. Option B is wrong because it suggests the output is the two numbers separated by a space, but the `+` operator concatenates them without a space. Option C is wrong because there is no TypeError; string concatenation with `+` is valid and produces a string result.

367
MCQmedium

What is the output of the code in the exhibit?

A.{5:'apple', 6:'banana', 6:'cherry'}
B.{'apple':5, 'banana':7, 'cherry':6}
C.{0:'apple', 1:'banana', 2:'cherry'}
D.{'apple':5, 'banana':6, 'cherry':6}
AnswerD

Correct mapping of items to their lengths.

Why this answer

The code creates a dictionary using the `dict()` constructor with a list of tuples. Each tuple is a key-value pair. The keys are strings ('apple', 'banana', 'cherry') and the values are integers (5, 6, 6).

The resulting dictionary is {'apple':5, 'banana':6, 'cherry':6}.

Exam trap

The PCEP exam often tests the distinction between `dict()` with a list of tuples versus other dictionary creation methods, and the trap here is that candidates mistakenly think the tuples are reversed or that keys are auto-generated as indices.

How to eliminate wrong answers

Option A is wrong because it shows integer keys (5, 6, 6) with string values, which reverses the order of the tuples. Option B is wrong because it assigns value 7 to 'banana', but the second tuple is ('banana',6), not ('banana',7). Option C is wrong because it shows auto-generated integer keys (0,1,2) with string values, which would only happen if the input were a sequence of values without explicit keys, not a list of key-value tuples.

368
MCQmedium

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

A.1 3
B.3.33 1
C.3 3
D.3 1
AnswerD

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

Why this answer

The // operator performs floor division, which divides 10 by 3 and discards the fractional part, yielding 3. The % operator returns the remainder of that division, which is 1. The print function outputs both values separated by a space, resulting in '3 1'.

Exam trap

Python Institute often tests the distinction between floor division (//) and true division (/), and the trap here is that candidates mistakenly think // performs regular division or confuse the order of quotient and remainder in the output.

How to eliminate wrong answers

Option A is wrong because it reverses the results, showing the remainder first (1) and the quotient second (3), which misinterprets the order of operations in the print statement. Option B is wrong because it uses true division (/) instead of floor division (//), giving 3.33, and incorrectly pairs it with remainder 1. Option C is wrong because it shows the quotient as 3 but incorrectly gives the remainder as 3, likely confusing the remainder with the divisor or the quotient itself.

369
MCQeasy

A developer writes code to iterate over a list and break when a certain condition is met. Which keyword is used to exit the loop prematurely?

A.break
B.stop
C.exit
D.continue
AnswerA

Correct keyword to exit a loop.

Why this answer

The `break` keyword is used in Python to immediately exit the nearest enclosing loop (for or while) when a specified condition is met, allowing the program to resume execution at the next statement after the loop. This is the standard mechanism for premature loop termination in Python, as defined in the language specification.

Exam trap

Python Institute often tests the distinction between `break` and `continue`, where candidates mistakenly think `continue` can exit a loop, but it only skips the current iteration and proceeds to the next one.

How to eliminate wrong answers

Option B is wrong because `stop` is not a Python keyword; it has no meaning in loop control and would raise a NameError if used. Option C is wrong because `exit` is a function (typically from the `sys` module) used to terminate the entire program, not just the loop, and is not a keyword for loop control. Option D is wrong because `continue` does not exit the loop; it skips the rest of the current iteration and jumps to the next iteration of the loop.

370
MCQmedium

A developer writes a Python script that calculates the average of a list of numbers. The script sometimes produces a ZeroDivisionError. Which of the following is the MOST appropriate way to handle this error to keep the script running?

A.Check if len(numbers) == 0 before division and skip calculation if true.
B.Use an if statement to check if the list is empty and print a warning message.
C.Remove the last element from the list if it is empty.
D.Wrap the division in a try/except block and catch ZeroDivisionError, then set the average to 0.
AnswerD

Handles the error gracefully and allows continuation.

Why this answer

It uses a try/except block to catch the ZeroDivisionError specifically, which is the most robust and Pythonic way to handle runtime errors. This approach keeps the script running by setting the average to 0 when the list is empty, without relying on pre-checks that might miss other causes of division by zero (e.g., if the sum is 0 but the list is not empty). In Python, exception handling is preferred for error-prone operations like division, as it separates normal logic from error handling cleanly.

Exam trap

Python Institute often tests the distinction between error prevention (e.g., if-checks) and error handling (e.g., try/except), where candidates mistakenly choose a pre-check that only partially addresses the error, while the correct answer uses exception handling to cover all cases.

How to eliminate wrong answers

Option A is wrong because checking len(numbers) == 0 before division only prevents the error for empty lists, but a ZeroDivisionError can also occur if the divisor is zero due to other reasons (e.g., a calculated denominator), making this approach incomplete. Option B is wrong because printing a warning message does not prevent the ZeroDivisionError from occurring; the script would still crash unless the division is skipped or handled. Option C is wrong because removing the last element from an empty list raises an IndexError, not a ZeroDivisionError, and it does not address the root cause of the division by zero.

371
MCQeasy

Which of the following is an immutable data type in Python?

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

Tuples are immutable.

Why this answer

A tuple is immutable because once created, its elements cannot be changed, added, or removed. This is enforced by Python's internal structure: tuples are stored as a fixed-length array of object references, and no methods exist to modify them in place.

Exam trap

Python Institute often tests the misconception that 'immutable' means the variable cannot be reassigned, when in fact it means the object's contents cannot be changed — a common trap that leads candidates to incorrectly label strings or tuples as mutable.

How to eliminate wrong answers

Option B is wrong because a set is mutable — you can add or remove elements using methods like add() and discard(). Option C is wrong because a list is mutable — you can modify, append, or delete elements via indexing, append(), or pop(). Option D is wrong because a dict is mutable — you can add, update, or delete key-value pairs using assignment or methods like pop() and update().

372
MCQeasy

Which of the following variable names is valid in Python?

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

Valid: underscores are allowed at the start.

Why this answer

(_count) is valid because Python allows identifiers to start with an underscore, and it contains only letters and underscores. Python variable names must start with a letter or underscore, followed by letters, digits, or underscores, and cannot be a reserved keyword.

Exam trap

Python Institute often tests the misconception that underscores are not allowed or that hyphens are acceptable in variable names, leading candidates to reject _count or accept my-var.

How to eliminate wrong answers

Option A is wrong because variable names cannot start with a digit; '1st_value' begins with '1', which violates Python's identifier rules. Option C is wrong because hyphens are not allowed in Python identifiers; 'my-var' uses a hyphen, which Python interprets as a subtraction operator. Option D is wrong because 'class' is a reserved keyword in Python used to define classes, so it cannot be used as a variable name.

373
MCQeasy

A developer writes: x = 5; y = 2.0; z = x / y; print(type(z)). What is the output?

A.<class 'str'>
B.<class 'int'>
C.TypeError
D.<class 'float'>
AnswerD

x / y returns a float because y is float.

Why this answer

In Python, the division operator (/) always returns a float, even when dividing two integers. Here, x is an integer (5) and y is a float (2.0), so the result is a float (2.5). The type() function returns <class 'float'>, making D correct.

Exam trap

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

How to eliminate wrong answers

Option A is wrong because the result of division is a number, not a string; type() would never return <class 'str'> for a numeric operation. Option B is wrong because Python 3's / operator always produces a float, even if the division is exact (e.g., 5/5 returns 1.0, not 1). Option C is wrong because there is no TypeError; Python allows division between int and float without issue, implicitly converting the int to a float for the operation.

374
MCQmedium

An accountant uses a Python script to calculate tax: tax = price * 0.08. For price=19.99, tax results in 1.5992. However, the output should be rounded to two decimal places. Which expression should replace the current one?

A.tax = round(price * 0.08)
B.tax = round(price * 0.08, 2)
C.tax = price * 0.08
D.tax = int(price * 0.08 * 100) / 100
AnswerB

Correctly rounds to two decimal places.

Why this answer

The built-in `round()` function with a second argument of 2 rounds the floating-point result of `price * 0.08` to exactly two decimal places, which matches the requirement for currency formatting. The other options either omit rounding, round to an integer, or use integer truncation that can produce incorrect results for negative numbers or edge cases.

Exam trap

Python Institute often tests the distinction between `round(x)` (rounds to integer) and `round(x, n)` (rounds to n decimal places), and the trap here is that candidates may choose Option A thinking it rounds to two decimals, or Option D thinking integer truncation is equivalent to rounding.

How to eliminate wrong answers

Option A is wrong because `round(price * 0.08)` with no second argument rounds to the nearest integer (0 decimal places), producing 2 instead of 1.60. Option C is wrong because it simply computes the raw floating-point value 1.5992 without any rounding, leaving extra decimal places. Option D is wrong because `int(price * 0.08 * 100) / 100` truncates toward zero, which for positive values works here but fails for negative numbers (e.g., -19.99 would give -1.59 instead of -1.60) and does not perform proper rounding.

375
MCQhard

A developer is using a lambda function that takes two arguments and returns their sum. Which of the following lambda expressions is correct?

A.lambda a, b: a + b
B.lambda a, b: a - b
C.lambda a, b: return a + b
D.def add(a, b): return a + b
AnswerA

Correct. The expression 'lambda a, b: a + b' is a valid lambda function that sums two arguments.

Why this answer

Option A correctly defines a lambda function that takes two arguments and returns their sum. Option B is a valid lambda but returns the difference (a - b), not the sum, so it does not meet the requirement. Option C is incorrect because lambda expressions cannot include a `return` statement; the result is implicitly returned.

Option D uses `def` to define a named function, not a lambda.

Exam trap

Python Institute often tests the misconception that lambda requires an explicit `return` statement, leading candidates to choose Option C, but in reality the expression after the colon is automatically returned.

How to eliminate wrong answers

Option B is wrong because it is syntactically identical to Option A, but the question asks for 'which of the following lambda expressions is correct' and only one answer is marked as correct; in this context, Option B is a duplicate and not the intended correct choice. Option C is wrong because it uses `return` inside a lambda, which is invalid syntax — lambda bodies can only contain a single expression, not a statement like `return`. Option D is wrong because it is a regular function definition using `def`, not a lambda expression, so it does not meet the requirement of being a lambda.

Page 4

Page 5 of 7

Page 6

All pages