Courseiva

Certified Entry-Level Python Programmer PCEP (PCEP) — Questions 301–375

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

Page 4

Page 5 of 7

Page 6
301
MCQmedium

A programmer writes the following code: `x = 7` then `y = 2` then `z = x / y`. What is the data type and value of `z`?

A.`float` with value `3.5`
B.`int` with value `4`
C.`int` with value `3`
D.`float` with value `3.0`
AnswerA

In Python 3, the `/` operator performs true division and always returns a `float`, regardless of operand types. With `x = 7` and `y = 2`, the result is `3.5`, a floating-point number. This is a key difference from Python 2, where integer division with `/` would yield an integer. Here, the type is `float` and the value is `3.5`.

Why this answer

In Python 3, the division operator `/` always returns a float, even when dividing two integers that yield a whole number. For `x = 7` and `y = 2`, the result is `3.5`, stored as a `float`. This behavior differs from Python 2, where `/` performed integer division for integers.

The `//` operator performs floor division and returns an integer when both operands are integers, but that is not used here.

Exam trap

The trap here is assuming that division of two integers returns an integer, perhaps due to experience with other programming languages or Python 2.

302
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

Assignment binds y to the same list object as x, not a copy. Calling append(4) mutates that shared object in place, so both names observe the change and printing x outputs [1, 2, 3, 4].

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

303
MCQmedium

A Python programmer is working with a list of strings called words. The programmer wants to create a new list that contains the lengths of each word, but only for words that have more than three characters. Which code snippet correctly produces this list?

A.lengths = [len(word) for word in words if len(word) > 3]
B.lengths = [] for word in words: if len(word) > 3: lengths.append(word) lengths.append(len(word))
C.lengths = [word for word in words if len(word) > 3]
D.lengths = [len(word) for word in words if word > 3]
AnswerA

This list comprehension iterates over each word in words, checks if the length of the word is greater than 3, and if so includes len(word) in the new list. It correctly filters and transforms the data in a single concise expression.

Why this answer

The correct snippet must filter words with more than three characters and then transform each remaining word into its length. The list comprehension that uses len(word) in the expression and filters with len(word) > 3 accomplishes both steps correctly. Other options either compare the wrong types, return the wrong data, or incorrectly append both words and lengths.

Exam trap

The trap here is comparing a string to an integer, which is invalid, or forgetting to apply the length transformation.

304
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

Python's `and` binds tighter than `or`, so `1 and 2` evaluates first. Since 1 is truthy, `and` returns its second operand, 2. That truthy result short-circuits the `or`, so 3 is never evaluated, satisfying the stem's precedence and short-circuit constraints.

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

305
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

A dictionary maps JSON objects directly: keys become strings and values become nested dictionaries, lists or scalars. This mirrors the exhibit's key-value pairs, satisfying the requirement to represent the configuration faithfully while allowing lookup by key rather than by positional index.

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.

306
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

Python evaluates conditions top-down and stops at the first true branch. If the 'B' condition (for example score >= 80) precedes the 'A' condition, a score of 90 matches 'B' first, so ordering the 'A' check earlier fixes it.

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.

307
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

Assigning `x = 5` inside `func` creates a new local variable, so the printed value within the function is 5. The module-level `x` remains 10, since Python resolves names by local-then-global scope and the assignment never rebinds the global. Hence the output is 5, then 10.

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.

308
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

Returning a, b packs the two values into a single tuple, which the caller can unpack directly. Python has no multi-value return type, so the tuple is the mechanism that satisfies the requirement to return multiple values from one function.

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.

309
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

String repetition with the `*` operator concatenates the original sequence three times, producing `abcabcabc`. This satisfies the stem's requirement to determine the exact output of the multiplication expression, since `"abc" * 3` yields the repeated string rather than raising an error or returning a numeric result.

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.

310
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

Python's + operator does not coerce types, so adding int 3 to str '4' raises TypeError. The operands must share a compatible type for concatenation or addition, and no implicit conversion occurs between int and str.

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.

311
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

The loop condition depends on a variable that must change each iteration to eventually become false. If that variable is never reassigned inside the loop body, the condition stays true forever, so the loop never terminates and 'Done' is never reached.

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.

312
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

Dictionaries are accessed by subscript, not by calling them as functions. Writing `rule('action')` attempts to invoke the dict as a callable, raising `TypeError: 'dict' object is not callable`, so the loop aborts before printing. Using `rule['action']` retrieves the value and satisfies the 'allow' filter.

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.

313
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

The empty parameter list satisfies the no-arguments constraint, and the bare `return 42` supplies the required value. Python permits a single-line suite after the colon, so this definition is syntactically valid and returns the integer 42 when called as `f()`.

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.

314
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

Division precedes addition, so b / 2 evaluates first as 4 / 2, yielding the float 2.0. Adding a (3) gives 5.0, and because true division always returns a float, the result is 5.0 rather than integer 5.

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.

315
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

The division operator in Python 3 always performs true division, returning a float regardless of whether operands are integers. So 5 / 2 yields 2.5, typed as float, not int. Floor division (//) would return an integer instead.

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.

316
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

extend() accepts an iterable and appends each of its elements individually to the end of the list, so [5,6] adds two separate items. This is a genuine list method that mutates the list in place, satisfying the valid-operation criterion.

Why this answer

Option B, my_list.extend([5,6]), is valid because Python lists provide the extend() method, which appends each element of the given iterable to the end of the list, so [5,6] adds two separate items. Option D, my_list.insert(0,5), is valid because insert(index, value) is a standard list method that places the value 5 at index 0, shifting existing elements to the right. Option E, my_list.append(5), is valid because append() is the canonical list method for adding a single element to the end of the list.

Option A, my_list.add(5), is not a list operation; add() belongs to set objects, not lists. Option C, my_list.push(5), is not a Python list method; push() is associated with stack-like structures in other languages (e.g., JavaScript arrays), whereas Python lists use append().

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.

317
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 missing key with subscript notation raises KeyError, because dictionaries do not return a default for absent keys. The stem's `user` dictionary holds only `'id'` and `'name'`, so `user['email']` fails immediately at runtime rather than returning `None`.

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.

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

319
MCQmedium

A warehouse script stores stock quantities in the list levels = [4, 0, 7, 0, 2]. A developer wants to build a new list, in_stock, containing only the quantities greater than zero, preserving the original order. Which code correctly produces [4, 7, 2]?

A.in_stock = [levels[q] for q in levels if q > 0]
B.in_stock = [q for q in levels if q >= 0]
C.in_stock = [q if q > 0 for q in levels]
D.in_stock = [q for q in levels if q > 0]
AnswerD

This list comprehension iterates over levels in order and keeps each quantity only when q > 0, so zeros are filtered out and 4, 7, and 2 are collected in their original sequence. The result is a brand-new list, leaving levels unchanged. It is the idiomatic single-expression way to filter a list in Python.

Why this answer

A comprehension of the form [expression for item in iterable if condition] walks the list in order and includes only items satisfying the condition. Testing q > 0 excludes the zeros while keeping 4, 7, and 2 in their original positions, and it builds a separate list rather than modifying the source.

Exam trap

The trap here is confusing the comprehension's filtering if clause with a conditional expression, which would additionally require an else branch.

320
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

A `finally` block's `return` overrides any `return` in the `try` block, so the value 2 replaces the pending 1 before the function exits. Python discards the earlier return value once `finally` executes its own `return`, making 2 the printed output.

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.

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

322
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

The built-in `input()` function reads a line from standard input, pauses execution until the user presses Enter, and returns the entered text as a string. This directly satisfies the Python 3 requirement, unlike `raw_input()`, which was renamed to `input()` in Python 3 and no longer exists.

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

323
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

The loop prints i while i is below 5, but the break statement exits immediately when i equals 3, before that value is printed. Output is therefore 0, 1 and 2, terminating earlier than the expected 0 through 4.

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.

324
MCQmedium

A cashier script stores a price as a string and needs to apply a 10 percent discount. The code is: price = "19.99" discount = 0.10 final = price * (1 - discount) print(final) What happens when this code runs?

A.It prints "19.99" repeated zero times, resulting in an empty string.
B.It prints 199.9 because the decimal point is ignored during multiplication.
C.It raises a TypeError because a string cannot be multiplied by a float.
D.It prints 17.991 because Python converts the string automatically.
AnswerC

Multiplying a str by an int repeats the string, but multiplying a str by a float is unsupported and raises TypeError. Since price is still the string "19.99" and (1 - discount) evaluates to the float 0.9, the * operator fails. The script must convert price with float(price) before the arithmetic can succeed.

Why this answer

The * operator supports string repetition only when the other operand is an integer. Here the other operand is the float 0.9, so Python raises TypeError. To compute the discounted price the code must first convert the string to a number, for example float(price) * (1 - discount), and only then print the result.

Exam trap

The trap here is expecting Python to convert numeric-looking strings to numbers automatically during arithmetic, which it never does.

325
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

The modulo operator accepts mixed numeric types in Python, so `x % y` with an integer and a float is valid and evaluates to 1.0. This satisfies the stem's requirement for true statements after execution, since no type restriction prevents combining int and float operands in arithmetic.

Why this answer

Option A is correct because x % y uses the modulo operator on an int and a float, which is valid in Python and yields the float remainder 1.0. Option B is correct because x / y performs true division (10 / 3.0), producing the float value approximately 3.3333333333333335. Option E is correct because x // y performs floor division; with a float operand the result is a float, so 10 // 3.0 equals 3.0.

Option C is not correct because w is a float (3.0), not an int, since one operand is a float. Option D is not correct because the / operator always returns a float in Python 3, not an integer.

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.

326
MCQmedium

A developer writes a function to log sensor readings. The function is defined as: def log_reading(sensor_id, value, unit="C"): return f"{sensor_id}: {value}{unit}" The developer calls log_reading("T1", 22, unit="F"). What is the result?

A.A SyntaxError because keyword arguments must come before positional arguments.
B.A TypeError because the function expects three arguments and only two positional arguments were given.
C."T1: 22C"
D."T1: 22F"
AnswerD

The function has a default parameter unit with default value "C", but the caller explicitly passes unit="F" as a keyword argument. This overrides the default, so the returned string uses "F" as the unit. The value 22 is passed positionally to the value parameter. Therefore, the f-string evaluates to "T1: 22F".

Why this answer

The function call provides two positional arguments ("T1" and 22) and one keyword argument (unit="F"). The keyword argument overrides the default value "C". The f-string then interpolates sensor_id, value, and unit, producing "T1: 22F".

This demonstrates how default parameters can be overridden by explicit keyword arguments in a function call.

Exam trap

The trap here is assuming that a default parameter value always takes precedence or that keyword arguments cannot override defaults.

327
Drag & Dropmedium

Order the steps to define a class and create an object in Python.

Drag or tap steps into the slots.

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.

328
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

int(input('Age: ')) converts the string returned by input() into an integer, enabling numeric comparison. The condition age >= 18 then prints 'Adult' when the age is 18 or above, satisfying the stem's requirement of handling users aged 18 or older.

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

329
MCQeasy

A student is analyzing Python code and wants to understand the result of the expression `2 ** 3 ** 2` in Python 3. What value does this expression produce?

A.36
B.512
C.128
D.64
AnswerB

The exponentiation operator (**) in Python is right-associative, so 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2). First, 3 ** 2 equals 9; then 2 ** 9 equals 512. Thus, the expression yields 512, demonstrating the right-associative grouping of the ** operator.

Why this answer

The exponentiation operator (**) in Python is right-associative, meaning that in a chain like 2 ** 3 ** 2, the rightmost operation is performed first. This gives 2 ** (3 ** 2) = 2 ** 9 = 512. Understanding associativity prevents errors when chaining exponentiation without parentheses.

Exam trap

The trap here is assuming that exponentiation is left-associative, which would lead to computing (2 ** 3) ** 2 = 64 instead of the correct right-associative result.

330
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

The modulo operator returns the remainder after integer division, so 10 % 3 evaluates to 1 because 3 divides into 10 three times with 1 left over. This satisfies the stem's requirement to predict the printed output of the expression.

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.

331
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

Python uses indentation to delimit blocks, and every statement within the same block must share identical leading whitespace. Mixing tabs and spaces or varying indent width within one block raises an IndentationError, so consistency is mandatory rather than stylistic.

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.

332
MCQmedium

A developer writes the following code to sum a list of scores: scores = [12, 7, 25, 18] total = 0 for s in scores: total += s print(total) What is printed?

A.[12, 7, 25, 18]
B.62
C.12
D.0
AnswerB

The loop iterates over each element of scores and adds it to total using the augmented assignment +=. The running sum becomes 12, then 19, then 44, then 62. After the loop finishes, print displays the accumulated total, which is 62. This correctly sums all four values in the list.

Why this answer

The for loop visits every item in the scores list, and the augmented assignment total += s adds each score to the running sum. Starting from zero, the additions produce 12, 19, 44, and finally 62, which is the value printed after the loop completes.

Exam trap

The trap here is misreading total += s as an assignment that replaces total each pass, when it actually accumulates the running sum.

333
MCQeasy

A student writes the following code: name = "Alice" age = 25 print("Name: " + name + ", Age: " + age) What happens when the code runs?

A.It raises a SyntaxError before execution.
B.It prints: Name: Alice, Age: age
C.It prints: Name: Alice, Age: 25
D.A TypeError is raised because you cannot concatenate a string and an integer.
AnswerD

The + operator between a string and an integer is not allowed. Python raises a TypeError with a message like 'can only concatenate str (not "int") to str'. The age variable is an integer, so the concatenation fails at runtime.

Why this answer

In Python, the + operator cannot combine a string and an integer. The expression attempts to concatenate the string literal with the integer variable age, which raises a TypeError. To fix this, the integer must be converted to a string using str(age) or formatted using an f-string or the format() method.

Exam trap

The trap here is thinking that Python automatically converts types during string concatenation, as some languages do, when in fact it requires explicit conversion.

334
MCQeasy

A Python script contains the following code: price = 19.99 quantity = 3 total = price * quantity print(type(total)) What is displayed when this script runs?

A.<class 'str'>
B.59.97
C.<class 'float'>
D.<class 'int'>
AnswerC

In Python, when an int and a float are combined with the multiplication operator, the int is converted to a float and the result is a float. Since price is 19.99, a float, multiplying it by the integer quantity produces a float value, and type() reports the class of that result as float.

Why this answer

The multiplication of a float and an int in Python produces a float because Python applies numeric type promotion, converting the integer operand to a float before the operation. The variable total therefore holds a float, and type(total) displays the class object for floats. Integer output would require both operands to be int, and string output would require quoted text.

Exam trap

The trap here is assuming that multiplying a decimal literal by a whole number returns an integer merely because the product has no fractional part shown.

335
MCQhard

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

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

Slicing extracts characters from index 0 up to, but excluding, index 3, yielding "Hel". The start index defaults to 0, and the stop index is exclusive, so the character at position 3 ("l") is omitted. This satisfies the stem's requirement to print the first three characters of "Hello".

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.

336
MCQhard

A programmer writes the following code to classify a temperature reading: temp = 25 if temp > 30: print('Hot') elif temp > 20: print('Warm') else: print('Cool') What is printed when this code runs?

A.Cool
B.Nothing is printed because the code has a syntax error.
C.Warm
D.Hot
AnswerC

The first condition temp > 30 evaluates to False because 25 is not greater than 30. The elif condition temp > 20 evaluates to True because 25 is greater than 20. Therefore, the block under elif executes, printing 'Warm'. The else block is skipped. This is the correct output.

Why this answer

The if-elif-else structure evaluates conditions top-down. Since temp is 25, the first condition (temp > 30) is false, the second (temp > 20) is true, so the 'Warm' branch executes. The else is bypassed.

The other outputs would occur only if the temperature fell into different ranges or if the code were invalid.

Exam trap

The trap here is misreading the boundary conditions or assuming the first condition is true without checking the actual value of temp.

337
MCQmedium

A Python developer is writing a script to process a list of order IDs. The script must skip any order ID that is an empty string and continue processing the remaining IDs. Inside a `for` loop over the list, which statement should be used to skip the current iteration when an empty string is encountered and proceed with the next order ID?

A.pass
B.continue
C.exit
D.break
AnswerB

`continue` skips the rest of the current iteration and jumps to the next item in the loop. When an empty string is detected, executing `continue` abandons processing for that order ID and moves directly to the next one, exactly matching the requirement to skip blanks while continuing through the list.

Why this answer

The `continue` statement abandons the current iteration and proceeds with the next element, which is the correct behavior for skipping empty order IDs while still processing the rest of the list. `break` would stop the loop entirely, `pass` does nothing, and `exit` would terminate the interpreter, so none of those match the filtering requirement.

Exam trap

The trap here is choosing `break` when the intent is to skip only the current item; `break` ends the whole loop, while `continue` moves to the next iteration.

338
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 count from the end, so -3 maps to index 2 (value 3) and -1 maps to index 4 (value 5). Slicing excludes the stop index, returning elements at positions 2 and 3, giving [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:].

339
MCQmedium

A logistics analyst maintains a list `weights` representing the mass of parcels in kilograms. The analyst needs to determine how many parcels weigh more than 10 kg, but the list also contains a few `None` values that indicate missing measurements and must not be counted. Which code correctly counts only the parcels heavier than 10 kg while ignoring missing entries?

A.count = 0 for w in weights: if w is not None and w > 10: count += 1
B.count = 0 for w in weights: if w > 10: count += 1
C.count = sum(1 for w in weights if w > 10)
D.count = 0 for w in weights: if w > 10 or w is None: count += 1
AnswerA

The condition first checks that the element is not None, short-circuiting before the numeric comparison. This prevents a TypeError on missing measurements and correctly increments the counter only for parcels whose weight exceeds 10 kg. It satisfies both requirements: counting heavy parcels and ignoring None entries, using standard Python truth evaluation.

Why this answer

The correct code uses a combined condition that first verifies the element is not None, then compares it with 10. This ordering exploits short-circuit evaluation so that None never reaches the numeric comparison. As a result, only actual numeric weights greater than 10 increment the counter, and missing measurements are silently skipped as required by the analyst.

Exam trap

The trap here is assuming that a simple numeric comparison will automatically skip None values, when in fact comparing None with an integer raises a TypeError.

340
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

The inner loop breaks only when i equals j, so for i=0 and i=1 the else clause is skipped. For i=2, j never equals 2, so the inner loop completes and the else runs, printing '2 outer'.

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

341
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

Python evaluates except clauses in written order, and a specific handler takes precedence over a bare except. Since ValueError matches the named clause first, that handler runs; the bare except only catches exceptions no earlier clause matched.

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.

342
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

Skipping 3 occurs because the loop body executes `continue` when the counter equals 3, bypassing the `print()` call for that iteration while the loop proceeds to 4 and 5. Values 1, 2, 4 and 5 are therefore printed, matching the required output exactly.

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.

343
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

The crash occurs because `input()` always returns a string, so any arithmetic or numeric comparison on that value raises a `TypeError`. The stem's constraint is unhandled numeric use of raw input; converting with `int()` or `float()` before operating on the value resolves it.

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.

344
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 binds tighter than addition, so a + b + c / 3 computes a + b + (c/3), not (a+b+c)/3. Wrapping the sum in parentheses restores the intended grouping, satisfying the stem's requirement for a correct average calculation across all three numbers.

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.

345
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

The `range(1, 11)` call yields integers 1 through 10, since the stop value is exclusive, satisfying the inclusive upper bound. Each value is squared by the `x**2` expression and collected into a new list, producing exactly the ten required squares without filtering or conditional logic.

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.

346
MCQhard

A developer writes a function that reads an integer from a string and adds it to a running total. The code uses try: total += int(value) followed by except ValueError: total += 0. During testing, a value of '12.5' is supplied. What is the resulting behaviour?

A.The program terminates with an unhandled ValueError because except clauses cannot add to variables defined outside the function.
B.The conversion succeeds and total is increased by 12 because int truncates the decimal portion.
C.A TypeError is raised because the except clause names ValueError rather than the broader Exception class.
D.The ValueError handler runs, total is incremented by 0, and execution continues normally.
AnswerD

int('12.5') raises ValueError because the string contains a decimal point that int cannot parse. The except ValueError clause matches that exception, so its body executes and adds zero to the running total. Because the exception is handled, the program does not terminate; control resumes after the try-except statement, which is the intended graceful-degradation behaviour.

Why this answer

int applied to the string '12.5' cannot produce an integer and raises ValueError. The except ValueError clause matches that exception type, so its body runs, adding zero to the total and allowing execution to continue. The conversion does not silently truncate string decimals, and the handler is correctly typed to catch exactly this failure.

Exam trap

The trap here is confusing int's behaviour on a float object, where it truncates, with its behaviour on a string such as '12.5', where it raises ValueError.

347
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

Python determines a variable's type at assignment time from the object bound to it, with no type declaration required. The interpreter infers the type from the assigned value, which is the mechanism underlying dynamic typing rather than static annotation.

Why this answer

Option D is correct because Python is dynamically typed: when you write an assignment such as x = 42, the interpreter determines the type of the object (int) from the value on the right-hand side at runtime, without any explicit type declaration. Option E is correct because a name in Python is just a reference to an object, so the same variable can be rebound to an object of a different type later, e.g., x = 42 followed by x = 'hello' changes x from int to str at runtime. Option A is wrong because Python requires no type declarations; types are attached to objects, not to variable names.

Option B is wrong because Python performs type checking at runtime, not at compile time (the CPython compiler only produces bytecode and does not enforce types). Option C is wrong because a variable's type is not fixed after assignment; rebinding the name to a new object of another type is perfectly legal.

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.

348
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

A dictionary maps each string key directly to its associated list, giving O(1) average lookup by key. This satisfies the stem's requirement for string-keyed configuration where each key holds multiple allowed values, since lists preserve the ordered collection of values per key without needing separate parallel structures.

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.

349
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

`str` is a built-in Python data type representing immutable sequences of Unicode characters, satisfying the stem's requirement for a genuine data type. It is a core text type created via literals or `str()`, distinct from containers like `list` and `dict`, and is recognised by `isinstance("x", str)`.

Why this answer

Option A, str, is correct because str is Python's built-in immutable text/string type, used for sequences of Unicode characters. Option C, bool, is correct because bool is a built-in subclass of int representing the two truth values True and False. Option D, float, is correct because float is Python's built-in floating-point type, typically implemented as a C double for real numbers.

Option B, math, is not a data type but a standard-library module that provides mathematical functions. Option E, None, is not a data type but the singleton object None, whose type is NoneType.

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.

350
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

Age is a whole-number count of years, so int stores it exactly without floating-point rounding artefacts. A float would permit nonsensical fractional ages, while str would prevent arithmetic; int matches the discrete, countable nature of the value.

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.

351
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

Python's numeric equality compares values across int and float types, so 3 and 3.0 are equal despite differing types. The expression therefore evaluates to True, satisfying the question's requirement for an expression that yields True.

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

352
MCQmedium

A developer wants to create a dictionary that maps employee IDs to their department names. The IDs are integers, and departments are strings. Which of the following correctly creates such a dictionary?

A.employees = {101: "HR", 102: "IT"}
B.employees = dict(101: "HR", 102: "IT")
C.employees = dict(101="HR", 102="IT")
D.employees = dict([101, "HR"], [102, "IT"])
AnswerA

This uses a dictionary literal with integer keys and string values. The syntax {key: value, ...} is the standard way to create a dictionary. It correctly maps employee IDs (101 and 102) to department names ("HR" and "IT"). This is valid and creates the desired dictionary.

Why this answer

The dictionary literal {101: "HR", 102: "IT"} is the correct syntax for creating a dictionary with integer keys and string values. The dict() constructor can also be used, but keyword arguments cannot have integer names, and passing multiple positional arguments is invalid. The literal syntax is straightforward and commonly used for this purpose.

Exam trap

The trap here is confusing dictionary literal syntax with the dict() constructor's keyword argument syntax, or misusing the dict() constructor with multiple arguments.

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

354
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 yields a str, never a number, so the + operator concatenates the two strings rather than adding them. Entering 5 and 3 therefore produces '53', confirming that string concatenation, not arithmetic addition, is performed.

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.

355
MCQeasy

A student types the following into a Python 3 interactive session: >>> greeting = 'Hello' >>> greeting = greeting + ' World' >>> print(greeting) What is displayed?

A.Hello
B.HelloWorld
C.Hello World
D.A TypeError is raised
AnswerC

The name greeting is first bound to the string 'Hello'. The assignment greeting = greeting + ' World' concatenates the two strings and rebinds the name to the new string 'Hello World'. print then displays that value. Strings are immutable, so a new string object is created rather than modifying the original.

Why this answer

The second statement evaluates the right-hand side first: greeting still refers to 'Hello', so 'Hello' + ' World' produces a new string containing the space, and the name greeting is rebound to that value. The subsequent print call therefore outputs the combined text. Because str objects are immutable, reassignment replaces the reference rather than altering the original object in place.

Exam trap

The trap here is assuming that reassigning a string variable modifies the original string object instead of creating a new one and rebinding the name.

356
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 sequences, so elements retain their insertion position and can be retrieved by index, satisfying the stem's requirement for a true statement. This contrasts with unordered collections such as sets and dictionaries, where iteration order is not guaranteed by the data type itself.

Why this answer

Option A is correct because Python lists are ordered sequences: elements are stored in a defined index order (starting at index 0), and iteration, indexing, and slicing return them in that insertion order. Option C is correct because lists are mutable: after creation you can change them in place with operations such as append(), insert(), remove(), pop(), sort(), or item assignment like lst[0] = 5. Option B is wrong because lists are dynamically sized; they grow and shrink automatically as elements are added or removed.

Option D is wrong because immutability describes tuples (and strings), not lists, which support in-place modification. Option E is wrong because Python lists are heterogeneous and may hold objects of different types, e.g., [1, 'two', 3.0].

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.

357
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

The break statement immediately terminates the innermost enclosing loop, transferring control to the first statement after it. This matches the stem's requirement to exit prematurely once a condition is met, unlike continue, which skips only the current iteration.

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.

358
MCQmedium

A developer is writing a Python function that must accept any number of positional arguments and return their sum. The function should also work when called with zero arguments. Which function definition correctly achieves this?

A.def total(nums): return sum(nums)
B.def total(nums=0): return sum(nums)
C.def total(*nums): return sum(nums)
D.def total(*nums): return sum(*nums)
AnswerC

Using *nums in the parameter list collects all positional arguments into a tuple named nums, which works even when no arguments are passed (nums becomes an empty tuple). The built-in sum() then returns 0 for an empty tuple, satisfying the zero-argument requirement.

Why this answer

The function must handle any number of positional arguments, including zero. Using *nums in the function definition collects arguments into a tuple, and sum() correctly adds them, returning 0 for an empty tuple. Other options either restrict the number of arguments or incorrectly unpack the tuple.

Exam trap

The trap here is confusing the parameter syntax *nums (which collects arguments) with the call syntax sum(*nums) (which unpacks), leading to a TypeError when the tuple is empty or when elements are not iterable.

359
MCQeasy

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

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

Tuples are immutable: once created, their elements cannot be reassigned, added or removed, satisfying the stem's requirement for an immutable type. Unlike lists, which permit in-place mutation, a tuple's contents stay fixed for its lifetime, making it the correct choice among the options given.

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().

360
MCQeasy

Which of the following variable names is valid in Python?

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

A leading underscore is a legal identifier character in Python, so `_count` satisfies the naming rules. It is not a keyword, starts with a letter or underscore rather than a digit, and contains no illegal symbols, making it a valid variable name.

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.

361
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

Dividing an int by a float invokes Python's true division, which always yields a float regardless of whether the result is whole. Here 5 / 2.0 produces 2.5, so type(z) returns <class 'float'>. This satisfies the stem's mixed-type operand constraint, since int/float promotes to 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.

362
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

The built-in round() function returns a float rounded to the specified number of decimal places, so round(price * 0.08, 2) yields 1.6 for price=19.99, satisfying the two-decimal constraint. Unlike formatting, it changes the numeric value itself, keeping tax usable in further arithmetic.

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.

363
Multi-Selecthard

A Python programmer is analyzing a list of integers named numbers. The programmer wants to create a new list that contains only the even numbers from numbers, each multiplied by 10. Which two of the following code snippets correctly produce the desired list? (Choose two.)

Select 2 answers
A.result = [] for n in numbers: if n % 2 == 0: result.append(n * 10)
B.result = [n * 10 for n in numbers if n % 2 != 0]
C.result = [] for n in numbers: if n % 2 == 0: result.append(n) n = n * 10
D.result = [n * 10 for n in numbers if n % 2 == 0]
E.result = [n for n in numbers if n % 2 == 0] * 10
AnswersA, D

This snippet initializes an empty list, iterates over each number, checks if it is even using the modulo operator, and if so appends the number multiplied by 10 to the result list. It correctly filters and transforms the data as required.

Why this answer

The desired output requires filtering even numbers and then multiplying each by 10. The explicit for-loop with append and the list comprehension both correctly perform this filter-and-transform operation. The other options either select odd numbers, fail to multiply, or multiply the list itself instead of its elements.

Exam trap

The trap here is misreading the condition or misunderstanding list multiplication versus element-wise multiplication.

364
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

Python lambda syntax places parameters before the colon and the single return expression after it, with no return keyword. Writing lambda a, b: a + b correctly declares two parameters and returns their sum, matching the two-argument addition requirement exactly.

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.

365
MCQmedium

A student grades system: score = 85 if score >= 90: grade = 'A' elif score >= 80: grade = 'B' elif score >= 70: grade = 'C' else: grade = 'F' What grade is assigned?

A.C
B.A
C.B
D.F
AnswerC

With score 85, the first condition (>= 90) fails, so the elif chain evaluates sequentially. The second condition, score >= 80, is true, assigning grade = 'B'. Python stops at the first matching branch, so the remaining elif and else blocks are skipped entirely.

Why this answer

The code uses a cascading if-elif-else structure. Since score is 85, the first condition (score >= 90) is False, so it moves to the elif score >= 80 condition, which is True, assigning grade = 'B'. The remaining elif and else are skipped, making 'B' the correct grade.

Exam trap

The trap here is that candidates might mistakenly think the last matching condition (score >= 70) applies, ignoring that the elif chain stops at the first True condition, leading them to pick 'C' instead of 'B'.

How to eliminate wrong answers

Option A is wrong because 'C' would only be assigned if score >= 70 and score < 80, but 85 is not less than 80. Option B is wrong because 'A' requires score >= 90, and 85 does not meet that condition. Option D is wrong because 'F' is only assigned when all prior conditions are False, which would require score < 70, but 85 is greater than 70.

366
MCQmedium

A Python developer is building a quiz application. The program stores correct answers in a list named `key` and user responses in a list named `answers`. The developer wants to count how many positions match between the two lists, stopping the comparison as soon as the first mismatch is found so that a diagnostic message can be shown. Which control-flow statement should be used inside the loop to stop iterating immediately when a mismatch occurs?

A.return
B.continue
C.pass
D.break
AnswerD

`break` immediately terminates the innermost enclosing loop and transfers control to the first statement after the loop. When a mismatch is found, executing `break` stops further comparisons, allowing the program to exit the loop and present the diagnostic message without processing the remaining positions, which is exactly the stated behavior.

Why this answer

The `break` statement exits the nearest enclosing loop immediately, which is precisely what is needed to stop comparing list positions once the first mismatch appears. `continue` only skips one iteration, `pass` does nothing, and `return` leaves the whole function, so none of those produce the desired early loop termination while preserving subsequent code execution.

Exam trap

The trap here is confusing `continue` with `break`; `continue` skips only the current iteration and lets the loop proceed, so it cannot stop the comparison at the first mismatch as required.

367
MCQmedium

A student writes a program to classify a number: num = 7 result = num > 5 and num < 10 or num == 0 print(result) What is printed, and why?

A.True, because comparison operators are evaluated after logical operators.
B.False, because or is evaluated before and, making the expression False.
C.True, because and has higher precedence than or, so (num > 5 and num < 10) is evaluated first and is True.
D.False, because num == 0 is False and that makes the whole expression False.
AnswerC

Python gives and higher precedence than or, so the expression groups as (num > 5 and num < 10) or (num == 0). For num = 7, both comparisons in the first group are true, making the group True. Since True or anything is True, the whole expression evaluates to True. The precedence rule is the key to understanding the result.

Why this answer

Python's logical operators follow a precedence order with and binding tighter than or, and comparison operators binding tighter than both. The expression is grouped as (num > 5 and num < 10) or (num == 0). With num = 7, the first group is True, so the entire expression short-circuits to True, and that value is printed.

Exam trap

The trap here is misremembering operator precedence and assuming or is evaluated before and, which would flip the grouping and change the result.

368
MCQmedium

Refer to the exhibit. Which of the following shows the correct output?

A.3.3333333333333335 4 1
B.3.3333333333333335 3 1
C.3.0 3.0 1.0
D.3 3 0
AnswerB

Python's `/` operator always performs true division, yielding a float, so `10/3` produces 3.3333333333333335. The `//` operator performs floor division, truncating toward negative infinity, giving `10//3 == 3`. The `%` operator returns the remainder, so `10%3 == 1`. Printing each result on its own line matches the exhibit's expected output exactly.

Why this answer

The code `print(10/3)` performs floating-point division in Python 3, yielding `3.3333333333333335`; `print(10//3)` performs floor division, which truncates to the nearest integer less than or equal to the result, giving `3`; and `print(10%3)` computes the remainder of the division, which is `1`.

Exam trap

The trap here is that candidates often confuse the behavior of the `/` operator (which always returns a float in Python 3) with integer division from Python 2, or they misapply floor division and remainder operations, especially when dealing with positive integers.

How to eliminate wrong answers

Option A is wrong because it shows `4` for the floor division `10//3`, but floor division of 10 by 3 correctly yields `3`, not `4`. Option C is wrong because it shows `3.0` for both `10/3` and `10//3`, but `10/3` is a float with a fractional part, not exactly `3.0`, and `10//3` returns an integer `3`, not a float `3.0`. Option D is wrong because it shows `3` for `10/3`, but `10/3` returns a float `3.3333333333333335`, not an integer `3`, and it shows `0` for `10%3`, but the remainder of 10 divided by 3 is `1`, not `0`.

369
Multi-Selectmedium

Which TWO of the following are valid ways to create a variable with the integer value 100?

Select 2 answers
A.x = 0100
B.x = 100.0
C.x = int('100')
D.x = 100
E.x = '100'
AnswersC, D

Calling `int('100')` converts the string literal `'100'` into an integer object, which is then bound to the name `x`. This satisfies the stem's requirement for a variable holding the integer value 100, since `int()` parses the numeric characters and returns a genuine `int`, not a string.

Why this answer

Option C, x = int('100'), is correct because the int() constructor parses the string '100' and returns a genuine integer object with the value 100. Option D, x = 100, is correct because an unquoted numeric literal without a decimal point is directly an integer in Python, so x is bound to the int value 100. Option A, x = 0100, is not a valid way to get the integer 100 in Python 3, where a leading zero on a decimal literal is a syntax error (and in Python 2 it would denote octal 64, not 100).

Option B, x = 100.0, creates a float, not an integer, even though its numeric value equals 100. Option E, x = '100', creates a string containing the characters 1, 0, 0, not an integer.

Exam trap

Python Institute often tests the distinction between numeric literals (like `100`), string literals (like `'100'`), and type conversion functions (like `int()`), and the trap here is that candidates may mistakenly think a string with digits is automatically an integer or that a float literal like `100.0` is equivalent to an integer.

370
Multi-Selectmedium

A Python developer is validating a list of sensor readings stored in `readings`. The developer needs to build a new list containing only readings that are strictly greater than 10. Which two code fragments correctly produce a list of only the values greater than 10? (Choose two.)

Select 2 answers
A.filtered = [r for r in readings if r > 10 else r]
B.filtered = [r for r in readings if r > 10]
C.filtered = list(filter(lambda r: r > 10, readings))
D.filtered = [r for r in readings if r >= 10]
E.filtered = readings.filter(r > 10)
AnswersB, C

This list comprehension iterates over every element in `readings`, evaluates the condition `r > 10`, and includes only those elements for which the condition is true. The result is a new list preserving the original order of qualifying readings, which is exactly the filtered output the developer needs for sensor validation.

Why this answer

A list comprehension with a trailing `if r > 10` and the built-in `filter()` with a lambda both select exactly the elements satisfying the strict comparison, producing the required list. The other fragments either use an inclusive comparison that wrongly keeps 10, call a nonexistent list method, or use invalid comprehension syntax with an `else` clause in the filter position.

Exam trap

The trap here is mixing up strict and inclusive comparison operators and assuming lists expose a `filter()` method, when filtering is done with a comprehension or the built-in `filter()` function.

371
MCQeasy

What is the output from the interactive Python session?

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

Slicing `s[1:4]` extracts characters at indices 1, 2 and 3, giving `'ell'`, whose length is 3. The expression `s[0]` returns the first character `'h'`, not a count. Printing both yields `3 1`, satisfying the stem's request for the session's exact output.

Why this answer

The expression `10 // 3` performs integer (floor) division, which discards the fractional part and returns the integer quotient 3. The expression `10 % 3` returns the remainder of the division, which is 1. Therefore, the output is `3 1`, making option B correct.

Exam trap

Python Institute often tests the distinction between true division (`/`) and floor division (`//`), knowing that candidates may confuse the two or forget that integer division in Python 3 returns an integer, not a float.

How to eliminate wrong answers

Option A is wrong because it suggests `10 // 3` yields 3.333, which would be the result of true division (`10 / 3`) in Python 3, not floor division. Option C is wrong because it reverses the order of the results, outputting `1 3` instead of `3 1`. Option D is wrong because it claims the remainder is 0, but `10 % 3` correctly yields 1, not 0.

372
MCQhard

A system administrator is automating server configuration using Python. She has a dictionary: config = {'host': 'localhost', 'port': 8080, 'debug': True}. She needs to add a new key 'timeout' with value 30 if it does not already exist, but only if the 'debug' key is False. If 'debug' is True, she should not add 'timeout'. Additionally, she wants to ensure that the ordering of keys in the dictionary remains stable (insertion order). Which code snippet correctly implements this logic?

A.if not config.get('debug'): config.setdefault('timeout', 30)
B.if config.get('debug') == False: config.update({'timeout': 30})
C.if config['debug']: config['timeout'] = 30 else: pass
D.if config.setdefault('debug', False) == False: config['timeout'] = 30
AnswerA

Using `config.get('debug')` returns the stored boolean, so `not` inverts it: when `debug` is `True` the condition fails and `timeout` is skipped, satisfying the stem's constraint. `setdefault` inserts `'timeout': 30` only when the key is absent, and Python 3.7+ dictionaries preserve insertion order, keeping key ordering stable.

Why this answer

`config.get('debug')` returns `True` (the value of the 'debug' key), and `not True` evaluates to `False`, so the `if` block is not entered — thus 'timeout' is not added. If 'debug' were `False`, `not False` would be `True`, and `config.setdefault('timeout', 30)` would add the key only if it did not already exist, preserving insertion order (Python 3.7+ guarantees dict order).

Exam trap

The trap here is that candidates often confuse `dict.get()` with `dict.setdefault()` or misread the condition logic (e.g., thinking `if not config.get('debug')` checks for key existence rather than truthiness of the value), leading them to pick options that either add the key when 'debug' is True or use methods that overwrite existing keys.

How to eliminate wrong answers

Option B is wrong because `config.get('debug') == False` evaluates to `False` when 'debug' is `True` (the condition is never met), but more importantly, `config.update({'timeout': 30})` would overwrite an existing 'timeout' key, which violates the 'only if it does not already exist' requirement. Option C is wrong because `if config['debug']:` is `True` when 'debug' is `True`, so it would add 'timeout' unconditionally (the `else: pass` does nothing), which is the opposite of the required logic. Option D is wrong because `config.setdefault('debug', False)` returns the existing value `True` (not `False`), so the condition `== False` is `False` and the block is skipped, but more critically, `setdefault` would add 'debug' with value `False` if it were missing, which is not intended and could corrupt the configuration.

373
Drag & Dropmedium

Order the steps to debug a Python script using print statements.

Drag or tap steps into the slots.

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

Why this order

Debugging with print involves inserting prints, running, analyzing, and cleaning up.

374
MCQmedium

A developer writes the following code: a = 3; b = 2; c = a / b; d = a // b; e = a % b. What are the values of c, d, e?

A.c=1, d=1, e=1
B.c=1.5, d=1, e=0
C.c=1.5, d=1, e=1
D.c=1.5, d=1.5, e=0
AnswerC

True division a / b yields 1.5 as a float, floor division a // b yields 1, and modulo a % b yields 1. These three results match the stem's expected values c=1.5, d=1, e=1, correctly distinguishing the three division-related operators.

Why this answer

In Python, the / operator performs true division, yielding a float result (3/2 = 1.5). The // operator performs floor division, which for positive numbers truncates the decimal part, giving 1. The % operator returns the remainder of the division, which is 3 - (1 * 2) = 1.

Thus c=1.5, d=1, e=1.

Exam trap

The trap here is that candidates often confuse the / operator (true division) with the // operator (floor division) and mistakenly think // returns a float, or they miscalculate the remainder by assuming it is always the fractional part of the division.

How to eliminate wrong answers

Option A is wrong because it incorrectly uses integer division for c (c should be 1.5, not 1) and miscomputes e (e should be 1, not 1). Option B is wrong because it incorrectly states e=0; the remainder of 3 divided by 2 is 1, not 0. Option D is wrong because it incorrectly uses floor division for d (d should be 1, not 1.5) and misstates e=0.

375
MCQeasy

A developer is writing a Python inventory reconciliation script. They need to examine each element of a list named `stock` and, for every element, execute a block of code that updates a running total. They do not want the loop to terminate early under any condition. Which statement should be placed at the beginning of the loop body to iterate over every element in order?

A.for item in len(stock):
B.for item in stock:
C.for item in range(stock):
D.while item in stock:
AnswerB

This header iterates directly over each element contained in the `stock` list, assigning each value to `item` in order from index 0 to the final index. Because no break or early termination is included, the loop body runs once per element, which matches the requirement to update a running total for every entry without skipping or stopping.

Why this answer

Iterating over a list with `for item in stock:` visits every element in order and assigns each value to the loop variable, making it the direct way to process all entries without early exit. The alternatives misuse `range()`, `len()`, or `while` in ways that either raise errors or fail to traverse the list sequentially, so they cannot accomplish the reconciliation task.

Exam trap

The trap here is assuming that `range()` or `len()` can be used interchangeably with a list in a for loop header, when both actually require an integer and will raise a TypeError if given a list object.

Page 4

Page 5 of 7

Page 6

All pages