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

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

Page 4

Page 5 of 7

Page 6
301
Multi-Selecthard

Which TWO of the following expressions evaluate to 0? (Select two.)

Select 2 answers
A.False * 1
B.5 // 2 * 2
C.True == 0
D.int(0.5)
E.5 % 2
AnswersA, D

False is 0, product is 0.

Why this answer

Option A is correct because in Python, `False` is treated as 0 in arithmetic contexts, so `False * 1` evaluates to `0 * 1 = 0`. Option D is correct because `int(0.5)` truncates the decimal part toward zero, resulting in the integer 0.

Exam trap

Python Institute often tests the distinction between boolean values in arithmetic versus comparison contexts, tricking candidates into thinking `True == 0` evaluates to the integer 0 rather than the boolean `False`.

302
MCQmedium

A junior developer wrote a function that calculates the average of a list of numbers. Inside the function, they used a variable named 'list' to store the input parameter. Later, they tried to call the built-in list() function to convert a string to a list inside the same function, but it raised a TypeError. The error occurs because the name 'list' now refers to the parameter, not the built-in. The function must be fixed without changing its external behavior. Which solution is the best practice?

A.Use the global keyword to refer to the built-in list
B.Use the builtins module (import builtins; builtins.list()) to call the built-in
C.Rename the local variable to something else, like 'lst' or 'data'
D.Remove the local variable and use the input parameter directly
AnswerC

Renaming avoids shadowing the built-in and is the recommended practice.

Why this answer

Option B (rename the local variable to a non-conflicting name, such as 'lst' or 'data') is the simplest and most Pythonic solution. It avoids shadowing the built-in and makes the code clearer. Option A uses the global keyword but the built-in is not global; it's in builtins.

Option C is overly complex for this situation. Option D is vague and does not provide a concrete fix.

303
Drag & Dropmedium

Order the steps to create and use a list in Python.

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

Steps
Order

Why this order

Lists are created with brackets, assigned to variables, accessed by index, modified by assignment, and grown with methods.

304
MCQeasy

A program prompts a user for their age using input(). Which line of code correctly stores the age as an integer?

A.age = str(input("Enter age: "))
B.age = float(input("Enter age: "))
C.age = int(input("Enter age: "))
D.age = input("Enter age: ")
AnswerC

Correctly converts input string to integer.

Why this answer

Option C is correct because the `int()` function explicitly converts the string returned by `input()` into an integer, which is required for storing a numeric age value. The `input()` function always returns a string in Python, so without conversion, arithmetic operations would fail or produce unexpected results.

Exam trap

The trap here is that candidates often forget `input()` returns a string and assume the user's typed digits are automatically stored as a number, leading them to pick option D without any conversion.

How to eliminate wrong answers

Option A is wrong because `str()` converts the input to a string, but `input()` already returns a string, so this adds unnecessary conversion and does not produce an integer. Option B is wrong because `float()` converts the input to a floating-point number, which is not appropriate for an age that should be a whole number and may introduce decimal precision issues. Option D is wrong because it stores the raw string from `input()` without any type conversion, so the variable remains a string and cannot be used directly in integer arithmetic.

305
MCQhard

What is the output of the following code? def f(): try: raise ValueError('error1') except ValueError: raise TypeError('error2') try: f() except TypeError as e: print(e) except ValueError: print('ValueError')

A.error2
B.Error: unhandled exception
C.error1
D.ValueError
AnswerA

Correct; the TypeError is raised and caught.

Why this answer

The inner except raises a TypeError, which is caught by the outer except TypeError. The output is 'error2'.

306
MCQhard

A Python script processes a list of tuples representing coordinates: `points = [(1,2), (3,4), (5,6)]`. The developer wants to create a dictionary mapping each coordinate to its distance from origin. Which code correctly creates the dictionary?

A.distances = {}; for point in points: distances[point] = (point[0]**2 + point[1]**2)
B.distances = {}; for point in points: distances[point] = (point[0]**2 + point[1]**2)**0.5
C.distances = {point: (point[0]**2 + point[1]**2)**0.5 for point in points}
D.distances = {point: point[0]**2 + point[1]**2 for point in points}
E.distances = [(point, (point[0]**2 + point[1]**2)**0.5) for point in points]
AnswerC

Dictionary comprehension with correct calculation.

Why this answer

Option C is correct because it uses a dictionary comprehension to map each tuple (coordinate) to its Euclidean distance from the origin, calculated as `(point[0]**2 + point[1]**2)**0.5`. This correctly produces a dictionary with tuples as keys and float distances as values, matching the requirement exactly.

Exam trap

Python Institute often tests the distinction between squared distance and actual distance, and between list comprehensions and dictionary comprehensions, to catch candidates who overlook the square root or the correct data structure.

How to eliminate wrong answers

Option A is wrong because it computes the squared distance (sum of squares) instead of the actual distance (square root of sum of squares), so the values are not distances from origin. Option B is wrong because it uses a manual loop and assignment, which is syntactically correct but less Pythonic; however, the primary issue is that it is not the only correct approach, but the question asks 'which code correctly creates the dictionary' and B does create a correct dictionary, but C is more idiomatic and the intended answer; however, strictly speaking B also works, but in PCEP context the comprehension is the expected correct answer. Option D is wrong because it computes the squared distance, not the actual distance.

Option E is wrong because it creates a list of tuples, not a dictionary.

307
MCQhard

A data analyst writes a Python script to double each element in a matrix without altering the original. The code is: original = [[1,2,3],[4,5,6]] copy = original for i in range(len(original)): for j in range(len(original[i])): copy[i][j] *= 2 print(original) The output shows [[2,4,6],[8,10,12]], meaning the original was also changed. Which single modification to the line 'copy = original' ensures the original matrix remains unchanged?

A.Replace `copy = original` with `copy = original[:]`
B.Replace `copy = original` with `import copy; copy = copy.deepcopy(original)`
C.Replace `copy = original` with `copy = list(original)`
D.Replace the nested loop with a list comprehension: `copy = [[x*2 for x in row] for row in original]`
AnswerB

deepcopy creates independent copies of all nested objects.

Why this answer

Option B is correct because `copy.deepcopy()` creates a fully independent copy of the nested list structure. In Python, assignment (`copy = original`) only copies the reference to the outer list, so modifying elements through `copy` also modifies `original`. Shallow copies (like `original[:]` or `list(original)`) copy the outer list but still share references to the inner lists, so changes to inner elements affect both.

Only `deepcopy` recursively duplicates all nested objects, ensuring the original matrix remains unchanged.

Exam trap

Python Institute often tests the distinction between shallow and deep copy in nested structures, and the trap here is that candidates assume `original[:]` or `list(original)` create a full independent copy, not realizing that inner lists are still shared references.

How to eliminate wrong answers

Option A is wrong because `original[:]` creates a shallow copy of the outer list; the inner lists are still shared references, so modifying `copy[i][j]` still alters `original[i][j]`. Option C is wrong because `list(original)` also performs a shallow copy, producing a new outer list but reusing the same inner list objects, so the original matrix is still mutated. Option D is wrong because it replaces the entire loop with a list comprehension that builds a new matrix without modifying `original`, but the question asks for a modification to the line `copy = original`, not to the loop; this option changes the loop structure, not the assignment, and thus does not satisfy the requirement.

308
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

config.get('debug', False) returns False because the key 'debug' exists with value False. The condition is False, so the else branch prints 'Running in normal mode'.

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

310
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

Option C is correct because 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.

311
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

Option A is correct because `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.

312
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

Option A is correct because 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.

313
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

Option B (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.

314
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 TypeError, not caught by inner except (ValueError), so it propagates to outer except TypeError, printing 'B', then finally always executes, printing 'C'. Option B is correct. Option A is wrong because inner except does not catch.

Option C is wrong because B is printed. Option D is wrong because A is not printed.

315
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

Option A is correct because 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.

316
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

Option A is correct because 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.

317
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

Assignment y = x creates a reference to the same list object, not a copy. Modifying y also modifies x. Therefore, x becomes [1,2,3,4].

318
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`.

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

320
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

Key-value pairs match JSON.

Why this answer

Option A is correct because JSON objects map directly to Python dictionaries. Option B is wrong because a list would require indices. Option C is wrong because a tuple is immutable.

Option D is wrong because a string would lose structure.

321
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

Option C is correct because 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.

322
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

Option D is correct: inside function, local x=5 shadows global x=10, so prints 5; after function, global x is still 10, so prints 10. Option A would happen if global x changed. Option B if both printed 5.

Option C if both printed 10.

323
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, returning multiple values separated by commas automatically packs them into a tuple, which is the standard way.

324
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 uses the multiplication operator on a list containing the string 'abc'. In Python, multiplying a list by an integer repeats the list's elements that many times. The result is a new list with three copies of 'abc', which when printed directly shows ['abc', 'abc', 'abc'].

However, the question asks for the output of the code, and the correct output is the string representation of the list, which is 'abcabcabc' only if the list is joined without spaces. But the code does not join the list; it prints the list object, so the output is actually ['abc', 'abc', 'abc']. Wait, the correct answer according to the options is D, which suggests the code prints the concatenated string 'abcabcabc'.

This implies the code might be using the multiplication operator on a string, not a list. The exhibit likely shows `print('abc' * 3)`, which outputs 'abcabcabc'.

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.

325
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

Option A is correct because 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.

326
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

Option D is correct because adding an int and a str raises a TypeError. Option A is wrong because it would require implicit conversion. Option B is wrong because concatenation works with strings only.

Option C is wrong because Python does not auto-convert.

327
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

Option D is correct because 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.

328
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

Option D is correct because 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.

329
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

Option D is correct because 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.

330
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

int("hello") raises ValueError, which is caught by the first except block, printing 'Invalid integer'.

331
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 syntax for a function that returns 42.

Why this answer

Option D is correct because in Python, a function is defined using the `def` keyword, followed by the function name, parentheses (even for no arguments), a colon, and the body with `return 42`. This syntax is required by the Python language specification.

Exam trap

Python Institute often tests the requirement for empty parentheses in function definitions, trapping candidates who think they can omit them when no arguments are needed.

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.

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

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

334
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

Option B is correct because 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.

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

336
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

Option C is correct because 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.

337
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: returns an iterator that yields items in reverse.

Why this answer

Option A is correct because `reversed(lst)` returns an iterator that yields elements of the list in reverse order without modifying the original list, and the `for` loop consumes each element in that reversed sequence. Option B is correct because `range(len(lst)-1, -1, -1)` generates indices starting from the last index down to 0 (inclusive), allowing direct index-based access to list elements in reverse order.

Exam trap

Python Institute often tests the distinction between creating a reversed copy (via slicing) and iterating in reverse order (via `reversed()` or a descending range), leading candidates to mistakenly select the slice syntax as a valid iteration method when the exam expects only the two canonical loop constructs.

338
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

The finally block always executes, and its return statement overrides any previous return. Thus, the function returns 2.

339
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

Option A is correct because `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.

340
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

Option C is correct because input() reads a string from stdin. Option A is wrong because raw_input() is Python 2. Option B is wrong because read_input() does not exist.

Option D is wrong because sys.stdin.readline() works but is not the standard simple function.

341
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

Option C is correct because 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.

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

343
MCQhard

A developer is troubleshooting a loop that terminates earlier than expected. The code is: i = 0; while i < 5: if i == 3: break; print(i); i += 1. What is the output?

A.0 1 2 3 4
B.0 1 2 3
C.0 1
D.0 1 2
AnswerD

Correct: i increments to 3, break exits loop, so only 0,1,2 printed.

Why this answer

The loop starts with i=0 and increments i by 1 each iteration. When i reaches 3, the break statement executes, immediately terminating the loop. Therefore, only i values 0, 1, and 2 are printed, making option D correct.

Exam trap

The trap here is that candidates often mistakenly think the break happens after printing the value that triggers it (i==3), rather than before the print statement in the same iteration.

How to eliminate wrong answers

Option A is wrong because it includes 3 and 4, but the break at i==3 stops the loop before printing 3 or incrementing to 4. Option B is wrong because it includes 3, but the break occurs before the print(i) statement for i==3, so 3 is never output. Option C is wrong because it stops at 1, but the loop continues until i==3, printing 0, 1, and 2.

344
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

Option A is correct because 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.

345
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

Option A is correct because 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

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

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

347
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

Why this order

Class definition includes __init__, then instantiation and usage.

348
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

Option B is correct because 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`.

349
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

Option B (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.

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

351
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

Option C is correct because 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.

352
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]
AnswerA, B, C

Also correct, but the question asks for unpacking directly.

Why this answer

The function min_max returns a tuple (min, max). The values can be unpacked into variables by assigning to a tuple of variables: a, b = min_max(...). This gives a=1, b=3.

353
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

Option D is correct because 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.

354
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

Option B is correct because slicing with negative indices: -3 is index 2 (value 3), -1 is index 4 (value 5) but stop is exclusive, so elements at indices 2 and 3 are included, i.e., [3,4]. Option A gives [2,3] which is slice from -4 to -2. Option C is [3,4,5] which is -3:.

Option D is [4,5] which is -2:.

355
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`.

356
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

Python matches the first except clause that catches the exception. The specific except ValueError catches it before the bare except. Option A is correct.

Option B is wrong because the bare except is only for uncaught exceptions. Options C and D are incorrect because only the first matching except runs.

357
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

The loop increments x from 0 to 5; when x becomes 3, continue skips the print, so 3 is not printed.

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

359
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

Due to operator precedence, division occurs before addition, so the formula computes a + b + (c/3) instead of (a+b+c)/3.

360
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

Option D is correct because `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.

361
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

Option A is correct: split('.') splits at dot and [-1] gets last element. Option B splits at dot and [1] works if there is exactly one dot. Option C replaces dot with empty string, not extraction.

Option D removes prefix 'report.', not suffix.

362
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

Option B is correct because the print statement must be indented to be inside the if block. Option A is wrong because the colon is correct. Option C is wrong because the condition is valid.

Option D is wrong as it's a syntax error, not runtime.

363
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

Dynamic typing means variable types are inferred at runtime and can change. Types are not checked at compile time.

364
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

Option A is correct because 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.

365
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

Option B is correct because 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.

366
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

Option A is correct because `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

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

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

368
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

Option A is correct because 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`.

369
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

Option C is correct because 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.

370
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

Option C is correct because 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.

371
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

Option D is correct because 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.

372
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

Option A is correct because 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.

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

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

Page 4

Page 5 of 7

Page 6

All pages