Courseiva

Certified Entry-Level Python Programmer PCEP (PCEP) — Questions 376–450

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

Page 5

Page 6 of 7

Page 7
376
MCQhard

Refer to the exhibit. What is the output when the code is executed?

A.0 1 2
B.0 0 0
C.2 2 2
D.3 3 3
AnswerC

The loop rebinds the same variable each iteration, and the final assignment leaves it holding 2. Printing after the loop completes therefore emits 2 2 2, because all three print calls reference the variable's last value rather than capturing each iteration's value separately.

Why this answer

The code defines a tuple `t = (0, 1, 2)`. The `for` loop iterates over the tuple, but each iteration prints `t[2]`, which is the third element (index 2) with value 2. Since the value is constant, it prints '2' three times.

Hence the output is '2 2 2'.

Exam trap

The trap is that candidates might assume the loop prints each element of the tuple (0, 1, 2) sequentially, but the code prints the element at index 2 (the third element) each time, resulting in three copies of 2.

How to eliminate wrong answers

Option A is wrong because it assumes the loop prints the current element `x` (0, 1, 2) rather than the fixed index `t[0]`. Option B is wrong because it assumes `t[0]` changes during iteration or that the tuple is modified, but tuples are immutable and `t[0]` remains `2`. Option D is wrong because it assumes the loop runs three times and prints `t[0]` but mistakenly thinks `t[0]` is `3`, which is not an element of the tuple.

377
MCQhard

Consider: x = True; y = False; z = x and not y or x. What is the value of z?

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

Python evaluates 'not' first, giving not False = True; 'and' then yields True and True = True; finally 'or' gives True or True = True. So z is True, satisfying the boolean expression's precedence order.

Why this answer

The expression `x and not y or x` is evaluated with operator precedence: `not` has the highest precedence, then `and`, then `or`. Given `x = True` and `y = False`, `not y` evaluates to `True`. Then `x and True` is `True and True`, which is `True`.

Finally, `True or x` (where `x` is `True`) short-circuits to `True`. Thus, `z` is `True`.

Exam trap

Python Institute often tests operator precedence by combining `and`, `or`, and `not` in a single expression, trapping candidates who incorrectly assume left-to-right evaluation without respecting that `not` binds first, then `and`, then `or`.

How to eliminate wrong answers

Option B is wrong because `None` is a special value representing the absence of a value, but the expression always yields a boolean result, never `None`. Option C is wrong because there is no syntax or runtime error; all variables are defined and the operators are valid for boolean values. Option D is wrong because the expression evaluates to `True`, not `False`; a common mistake is misordering precedence or incorrectly evaluating `not y` as `False`.

378
MCQhard

A function is defined to accept a variable number of positional arguments and return their sum. The code is: def total(*args): return sum(args) What is the result of `total(1, 2, 3)`?

A.A tuple `(1, 2, 3)`
B.6
C.A TypeError is raised.
D.0
AnswerB

The function uses *args to collect all positional arguments into a tuple. When called with 1, 2, 3, args becomes (1, 2, 3). The built-in sum function then adds these numbers, resulting in 6. This is the correct output.

Why this answer

The *args parameter collects the positional arguments into a tuple. The sum function then adds the elements of that tuple. With arguments 1, 2, and 3, the sum is 6.

Thus, the function returns 6.

Exam trap

The trap here is thinking that the function returns the tuple of arguments, but it actually returns the computed sum.

379
Multi-Selectmedium

Which TWO of the following are valid ways to create a dictionary with initial key-value pairs? (Select exactly 2)

Select 2 answers
A.d = {'a': 1, 'b': 2}
B.d = ('a'=1, 'b'=2)
C.d = dict.fromkeys(['a', 'b', 'c']) # without value
D.d = dict(a=1, b=2)
E.d = dict(['a', 'b'], [1, 2])
AnswersA, D

Standard dictionary literal.

Why this answer

It uses the standard literal syntax for creating a dictionary with initial key-value pairs. The curly braces `{}` with colon-separated keys and values are the most common and direct way to define a dictionary in Python.

Exam trap

Python Institute often tests the distinction between the literal `{}` syntax and the `dict()` constructor, and candidates may mistakenly think that `dict()` can accept two separate lists as positional arguments, similar to how `zip()` works, or that parentheses can be used to define a dictionary.

380
MCQmedium

A developer writes a function that appends an item to a list: def add_item(item, my_list=[]): my_list.append(item); return my_list. They call add_item(1) twice. What are the return values of the two calls?

A.[1] and [1]
B.[1] and [1,1]
C.TypeError
D.[1] and [2]
AnswerB

The default list argument is evaluated once at function definition, so the same mutable list object persists across calls. The first call appends 1, returning [1]; the second appends to that same list, returning [1, 1]. This is Python's classic mutable default argument pitfall.

Why this answer

The default argument `my_list=[]` is evaluated only once at function definition time, not each time the function is called. Therefore, the first call `add_item(1)` appends 1 to the same list object, returning `[1]`. The second call appends another 1 to that same list, returning `[1, 1]`.

This is a classic Python gotcha involving mutable default arguments.

Exam trap

The PCEP exam often tests the mutable default argument trap — the trap here is that candidates mistakenly believe default arguments are re-evaluated on every function call, leading them to choose option A, when in fact they are evaluated only once at definition time.

How to eliminate wrong answers

Option A is wrong because it assumes the default list is recreated on each call, which is not how Python handles mutable default arguments — the list persists across calls. Option C is wrong because no TypeError occurs; the function is called correctly with a single positional argument, and the default list handles the missing second argument. Option D is wrong because it suggests the second call returns `[2]`, which would require the item argument to be 2 or some other mutation, but the same integer 1 is appended both times.

381
MCQmedium

What is the output of 'print(3 * "ab")'?

A.ab3
B.3ab
C.ababab
D.Error
AnswerC

String repetition by integer: the * operator repeats the string operand three times, concatenating "ab" with itself to yield "ababab". Python defines this for str multiplied by int, so no type error occurs and the six-character result prints directly.

Why this answer

In Python, the multiplication operator (*) when used with a string and an integer performs string repetition. The expression 3 * "ab" repeats the string "ab" three times, concatenating the copies into a single string "ababab". The print() function then outputs this resulting string to the console.

Exam trap

Python Institute often tests the distinction between the multiplication operator (*) for repetition and the plus operator (+) for concatenation, leading candidates to mistakenly think the integer is placed adjacent to the string rather than the string being repeated.

How to eliminate wrong answers

Option A is wrong because it suggests the integer 3 is appended to the string, which would require concatenation with +, not multiplication. Option B is wrong because it implies the integer is prepended, which is also a concatenation misconception. Option D is wrong because string repetition with an integer is a valid Python operation; it does not raise an error.

382
MCQmedium

A programmer wants to iterate over a list and also access the index. Which built-in function should they use?

A.zip()
B.map()
C.enumerate()
D.range()
AnswerC

enumerate() yields pairs of index and value while iterating, so the loop unpacks both without manual counter management. It satisfies the requirement to access the index directly, unlike range() combined with indexing or zip(), which needs a separate sequence.

Why this answer

The `enumerate()` function is the correct choice because it returns an iterator that yields pairs of (index, element) for each item in an iterable, allowing direct access to both the index and the value during iteration without manually managing a counter.

Exam trap

The PCEP exam often tests the distinction between `enumerate()` and `range(len())`, where candidates mistakenly think `range()` alone provides index access, but it only generates numbers and requires explicit indexing into the list.

How to eliminate wrong answers

Option A is wrong because `zip()` is used to aggregate elements from multiple iterables into tuples, not to provide index access. Option B is wrong because `map()` applies a function to every item of an iterable and returns an iterator of results, but does not supply index information. Option D is wrong because `range()` generates a sequence of numbers, which can be used to iterate over indices, but it does not directly pair indices with list elements; you would need to index the list separately, which is less efficient and more error-prone.

383
MCQeasy

Which function is used to read user input as a string?

A.read()
B.scan()
C.get()
D.input()
AnswerD

input() reads a line from standard input, strips the trailing newline, and returns it as a string. That matches the stem's requirement to read user input as a string, unlike functions that evaluate the entered text or read from files.

Why this answer

The `input()` function is the correct answer because it is the built-in Python function specifically designed to read a line of text from the user via standard input (stdin). It always returns the input as a string, regardless of whether the user types digits or other characters, making it the standard tool for console input in Python.

Exam trap

Python Institute often tests the distinction between `input()` and `raw_input()` (the Python 2 equivalent) or confuses candidates by listing file or dictionary methods like `read()` or `get()` as plausible input functions.

How to eliminate wrong answers

Option A is wrong because `read()` is a method of file objects (e.g., `file.read()`) used to read the contents of a file, not to read user input from the console. Option B is wrong because `scan()` is not a built-in Python function; it resembles the `scanf()` function from C, but Python has no such built-in. Option C is wrong because `get()` is a method of dictionary objects (e.g., `dict.get(key)`) used to retrieve a value for a given key, not for reading user input.

384
MCQeasy

A logistics analyst is writing a Python script that processes a list of shipment weights in kilograms. The analyst needs to display each weight one at a time and also know its position in the list, starting from 1 rather than 0. Which approach most directly accomplishes this?

A.Use for i in range(len(weights)): and print i and weights[i].
B.Use for weight in weights: and print weights.index(weight).
C.Use while weights: and pop the first element each time, printing its value.
D.Use for index, weight in enumerate(weights, start=1): and print index and weight.
AnswerD

The enumerate() function yields pairs of an index and the corresponding element from the iterable. By passing start=1, the counter begins at one instead of the default zero, matching the analyst's requirement to number shipments from 1. This is the idiomatic and most direct way to obtain both position and value in a single loop without manual counter management.

Why this answer

The enumerate() function is designed to pair each element of an iterable with a counter. Supplying start=1 shifts the counter so the first shipment is numbered 1. Other approaches either produce 0-based indexes, mutate the list, or require manual offset adjustments that are easy to get wrong.

Exam trap

The trap here is assuming that list.index() returns the current loop position rather than the first matching element's index.

385
MCQhard

What is the result of 'bool(0) and bool(1)'?

A.False
B.True
C.1
D.0
AnswerA

Evaluating `bool(0)` yields `False`, and Python's `and` operator short-circuits: when the left operand is falsy, it returns that operand immediately without evaluating `bool(1)`. The expression therefore evaluates to `False`, satisfying the question's requirement for the result of this boolean conjunction.

Why this answer

The expression `bool(0) and bool(1)` evaluates to `False` because `bool(0)` converts the integer 0 to `False` (since 0 is falsy in Python), and `bool(1)` converts 1 to `True`. The `and` operator returns `True` only if both operands are truthy; here, `False and True` yields `False`.

Exam trap

Python Institute often tests the distinction between boolean values and their integer equivalents (0 and 1), tricking candidates into thinking the result is an integer like `0` or `1` instead of the boolean `False` or `True`.

How to eliminate wrong answers

Option B is wrong because `True` would only result if both operands were truthy, but `bool(0)` is `False`, so the `and` operation short-circuits and returns `False`. Option C is wrong because `1` is an integer, but the result of `and` with boolean operands is a boolean (`False`), not an integer. Option D is wrong because `0` is an integer, but the expression returns the boolean `False`, not the integer `0`, even though `False` is falsy.

386
MCQmedium

What is the result of the following expression? 3 + 4 * 2 ** 3 // 5

A.9
B.7
C.6
D.11
AnswerA

Exponentiation binds tightest, giving 2 ** 3 = 8; then 4 * 8 = 32; floor division 32 // 5 = 6; finally 3 + 6 = 9. Precedence order is **, then * and //, then +.

Why this answer

The expression follows Python's operator precedence: exponentiation (`**`) has the highest precedence, then multiplication (`*`) and floor division (`//`) are evaluated left to right, and finally addition (`+`). First, `2 ** 3` computes to 8. Then `4 * 8` gives 32, and `32 // 5` yields 6 (floor division truncates toward negative infinity, but here it's positive).

Finally, `3 + 6` equals 9. Thus, option A is correct.

Exam trap

The PCEP exam often tests the combination of exponentiation, multiplication, floor division, and addition in a single expression to trap candidates who forget that `**` binds tighter than `*` and `//`, or who incorrectly apply left-to-right evaluation across all operators.

How to eliminate wrong answers

Option B (7) is wrong because it likely results from incorrectly evaluating `2 ** 3` as 6, then `4 * 6 = 24`, `24 // 5 = 4`, and `3 + 4 = 7`, misunderstanding exponentiation. Option C (6) is wrong because it probably comes from computing `3 + 4 = 7`, then `2 ** 3 = 8`, `7 * 8 = 56`, `56 // 5 = 11` (or some other misordering), or simply taking the floor division result `32 // 5 = 6` as the final answer, ignoring the addition. Option D (11) is wrong because it may arise from evaluating left to right without precedence: `3 + 4 = 7`, `7 * 2 = 14`, `14 ** 3 = 2744`, `2744 // 5 = 548`, or more plausibly `3 + 4 * 2 = 11`, then `11 ** 3 // 5` misapplied, or `3 + 4 * 2 = 11`, then `11 ** 3 = 1331`, `1331 // 5 = 266`, none of which match; the specific error is likely treating `*` and `**` with equal precedence or ignoring floor division truncation.

387
Multi-Selectmedium

Which THREE of the following code snippets will successfully print the string 'Hello, World!'? (Choose three.)

Select 3 answers
A.print('''Hello, World!''')
B.print("He said, "Hello!"")
C.print("Hello, World!")
D.print('It's a beautiful day')
E.print('Hello, World!')
AnswersA, C, E

Triple-quoted strings are valid Python string literals, so `'''Hello, World!'''` creates the same str object as single or double quotes and passes it to `print()`. The embedded apostrophe-free content needs no escaping, and the statement satisfies the stem's requirement to output exactly `Hello, World!`.

Why this answer

Option A is correct because triple-quoted strings ('''...''') are valid Python string literals, and since the content 'Hello, World!' contains no conflicting triple quotes, print('''Hello, World!''') outputs the string successfully. Option C is correct because a double-quoted string literal "Hello, World!" is valid Python syntax, and print("Hello, World!") outputs the exact text. Option E is correct because a single-quoted string literal 'Hello, World!' is valid Python syntax, and print('Hello, World!') outputs the exact text.

Option B is incorrect because the inner double quotes around Hello! terminate the string early, causing a SyntaxError. Option D is incorrect because the apostrophe in It's prematurely closes the single-quoted string, also causing a SyntaxError.

Exam trap

The PCEP exam often tests the distinction between string delimiters and the need for escaping quotes, trapping candidates who assume that any quote pair can contain the same quote character without escaping.

388
MCQeasy

A developer wants to use a tuple to store the names of the months. They attempt to change an element: months = ("Jan","Feb","Mar"); months[1] = "Februar". What is the result?

A.The tuple is updated to ("Jan","Februar","Mar")
B.A ValueError is raised
C.An AttributeError is raised
D.A TypeError is raised
AnswerD

Tuples are immutable sequences, so item assignment is unsupported. Attempting `months[1] = "Februar"` invokes the tuple's missing `__setitem__` behaviour, raising `TypeError: 'tuple' object does not support item assignment`. This satisfies the stem's constraint that the element change cannot succeed, unlike a list, which permits such mutation.

Why this answer

Tuples in Python are immutable, meaning their elements cannot be changed after creation. Attempting to assign a new value to an index of a tuple (e.g., months[1] = "Februar") raises a TypeError, not a ValueError or AttributeError. This is because the assignment operation is not supported for tuple objects.

Exam trap

The PCEP exam often tests the distinction between mutable (list) and immutable (tuple) types, and the trap here is that candidates confuse the immutability error with a ValueError or AttributeError, or assume tuples can be modified like lists.

How to eliminate wrong answers

Option A is wrong because tuples are immutable, so the assignment fails and the tuple remains unchanged; it is not updated. Option B is wrong because a ValueError is raised for operations like unpacking with wrong number of values or invalid literal conversion, not for attempting to modify an immutable object. Option C is wrong because an AttributeError occurs when accessing a method or attribute that does not exist on an object (e.g., months.append()), not when performing an assignment to an index.

389
MCQmedium

A programmer writes the following code to calculate the average of two numbers: a = 5 b = 2 avg = a / b print(avg) What is the output?

A.Error: division by zero
B.2
C.2.0
D.2.5
AnswerD

The division operator / in Python performs true division, returning a float result even when both operands are integers. Here, 5 / 2 equals 2.5. Therefore, the print statement outputs 2.5. This is the correct behavior for the / operator, which always returns a floating-point number.

Why this answer

In Python 3, the / operator performs true division and always returns a float. With a = 5 and b = 2, a / b evaluates to 2.5. The other options reflect common mistakes: confusing / with //, truncating the result, or assuming an error where none exists.

The correct output is 2.5.

Exam trap

The trap here is assuming that division of two integers yields an integer, as in some other programming languages, but Python's / operator always returns a float.

390
MCQmedium

A student is learning Python and writes a program to compute the area of a rectangle. The code: length = input("Enter length: ") width = input("Enter width: ") area = length * width print("Area:", area) When the user enters 5 and 3, the program crashes with a TypeError: can't multiply sequence by non-int of type 'str'. The student is puzzled because they thought input returns numbers. What is the correct explanation and fix?

A.The input function returns a string, so use int(input("Enter length: ")) and int(input("Enter width: ")).
B.The error is due to variable names length and width conflicting with built-in functions; rename them to l and w.
C.The print function cannot handle the multiplication result because area is a string; convert area to int.
D.The error can be fixed by using the eval function to directly evaluate the input as Python code.
AnswerA

`input()` always returns a `str`, so `length` and `width` hold `"5"` and `"3"`. Multiplying two strings is invalid, hence the `TypeError`. Wrapping each call in `int()` converts the text to integers, satisfying the arithmetic the area calculation requires.

Why this answer

The `input()` function in Python always returns a string, even if the user types a number. When you try to multiply two strings (or a string by a string), Python raises a `TypeError` because it cannot multiply sequences by non-integers. The fix is to explicitly convert the input to an integer using `int()` before performing arithmetic.

Exam trap

Python Institute often tests the misconception that `input()` returns a number when the user types digits, leading candidates to forget explicit type conversion, and they may incorrectly choose options that suggest renaming variables or using `eval()`.

How to eliminate wrong answers

Option B is wrong because `length` and `width` are not built-in function names; the error is purely a type mismatch, not a naming conflict. Option C is wrong because the error occurs during the multiplication, not in `print()`; converting `area` to `int` after the multiplication does not fix the root cause (the inputs are still strings). Option D is wrong because using `eval()` is dangerous and unnecessary; it evaluates arbitrary code and is not a recommended or safe way to convert input to numbers.

391
MCQhard

A developer is writing a function that retrieves a value from a nested dictionary based on a sequence of keys. If any key is missing, the function should raise a custom exception MissingKeyError with the missing key. The function signature is def get_nested(data, keys):. Which implementation correctly meets these requirements?

A.def get_nested(data, keys): for key in keys: if key not in data: raise MissingKeyError(key) data = data[key] return data
B.def get_nested(data, keys): for key in keys: data = data.get(key) if data is None: raise MissingKeyError(key) return data
C.def get_nested(data, keys): for key in keys: if key not in data: raise MissingKeyError data = data[key] return data
D.def get_nested(data, keys): try: for key in keys: data = data[key] return data except KeyError: raise MissingKeyError
AnswerA

This implementation iterates through the keys, checks if each key exists in the current dictionary, and raises MissingKeyError with the missing key if not. It then descends into the nested dictionary. This correctly handles missing keys at any level and returns the final value. It uses the 'in' operator to check membership, which is efficient for dictionaries.

Why this answer

The correct implementation must check each key's presence, raise MissingKeyError with the missing key, and traverse the nested structure. The chosen option does exactly that using the 'in' operator and passes the key to the exception. The others either omit the key in the exception, mishandle None values, or raise the exception class without arguments.

Exam trap

The trap here is using dict.get() and checking for None, which conflates missing keys with keys that have None values, or forgetting to pass the missing key to the custom exception.

392
MCQmedium

What will be printed? ```python my_list = [] my_list.append('192.168.1.10') my_list.append('255.255.255.0') my_list.append('192.168.1.1') print(my_list) ```

A.['255.255.255.0']
B.['192.168.1.10']
C.['192.168.1.10', '255.255.255.0', '192.168.1.1']
D.['192.168.1.10', '192.168.1.1']
AnswerC

append adds each string to the end of the list in call order, so the list holds the three addresses sequentially. Printing the list displays them in that insertion order within square brackets, with each element quoted as a string.

Why this answer

The printed output is a list containing three string elements: '192.168.1.10', '255.255.255.0', and '192.168.1.1'. When printing a list in Python, it displays each element enclosed in square brackets and separated by commas. Option C correctly shows this output.

The other options have an incorrect number of elements.

Exam trap

The PCEP exam often tests whether candidates understand that `append()` adds elements sequentially to the end of a list, and that printing the list shows all elements in order, not just the last one or a subset.

How to eliminate wrong answers

Option A is wrong because it only shows the subnet mask '255.255.255.0', ignoring the two IP addresses that were also appended. Option B is wrong because it only shows the first IP address '192.168.1.10', omitting the subnet mask and the gateway. Option D is wrong because it lists only the two IP addresses but leaves out the subnet mask '255.255.255.0' that was appended second.

393
MCQmedium

A program uses 'x = 3.14' and 'y = int(x)'. What is the value of y?

A.4
B.3.14
C.Error
D.3
AnswerD

Calling `int()` on a float truncates toward zero, discarding the fractional part rather than rounding to the nearest integer. For `x = 3.14`, the decimal `.14` is dropped, leaving exactly `3`. This satisfies the stem's requirement that `y` holds the integer conversion result of the float value.

Why this answer

The int() function in Python truncates the decimal part of a float, converting 3.14 to the integer 3. It does not round to the nearest whole number.

Exam trap

The trap here is that candidates often confuse int() with round() and assume it performs rounding to the nearest integer, leading them to choose option A (4) instead of the correct truncation result (3).

How to eliminate wrong answers

Option A is wrong because int() does not round up; it truncates toward zero, so 3.14 becomes 3, not 4. Option B is wrong because int() returns an integer, not a float; the value 3.14 would remain a float only if no conversion occurred. Option C is wrong because converting a float to an integer using int() is a valid operation in Python and does not raise an error.

394
MCQmedium

A company needs to filter a list of temperatures in Celsius to only those above 0, then convert to Fahrenheit (multiply by 9/5 and add 32). Which code snippet correctly accomplishes this using a list comprehension?

A.[t*9/5+32 for t in temps if t>0]
B.[t for t in temps if t>0 then t*9/5+32]
C.[t*9/5+32 for t in temps if t>0 else 0]
D.[t*9/5+32 for t in temps if t>0 else t]
AnswerA

Correct list comprehension with expression and filter.

Why this answer

It uses the standard list comprehension syntax: `[expression for item in iterable if condition]`. Here, `t*9/5+32` is the expression that converts Celsius to Fahrenheit, `for t in temps` iterates over the list, and `if t>0` filters out temperatures at or below zero. This produces a new list containing only the Fahrenheit equivalents of positive Celsius temperatures.

Exam trap

Python Institute often tests the distinction between the filter `if` (placed after the `for` clause) and the conditional expression `if-else` (placed in the expression part), and the trap here is that candidates mistakenly add an `else` to a filter-only comprehension, expecting it to work like a ternary operator.

How to eliminate wrong answers

Option B is wrong because it uses invalid syntax: `if t>0 then t*9/5+32` is not valid in Python list comprehensions; the `if` clause must come after the `for` clause and does not use `then`. Option C is wrong because it includes an `else 0` clause, which is not allowed in a filter-only list comprehension; the `if` at the end is for filtering, not conditional expression, and adding `else` causes a syntax error. Option D is wrong for the same reason: `else t` is invalid syntax when the `if` is used as a filter; a conditional expression (`x if condition else y`) must be placed in the expression part, not after the `if` filter.

395
MCQmedium

A developer defines a tuple `config = ('localhost', 8080, True)`. Later, the code attempts `config[1] = 9090`. What happens when this line executes?

A.The tuple is updated in place, and config becomes ('localhost', 9090, True).
B.The assignment succeeds only if the new value is of the same type as the old value.
C.A new tuple is created automatically with the updated value, and config is rebound to it.
D.A TypeError is raised because tuple objects do not support item assignment.
AnswerD

Tuples are immutable sequences. Any attempt to assign to an index, such as config[1] = 9090, raises TypeError with a message like 'tuple' object does not support item assignment. The tuple itself remains unchanged. This is the correct behavior for the given code.

Why this answer

Tuples are immutable, meaning their elements cannot be changed after the tuple is created. The statement config[1] = 9090 tries to assign to an index, which triggers a TypeError. No automatic rebinding or type-based exception occurs.

To change a value, you must build a new tuple and assign it to the variable.

Exam trap

The trap here is assuming that because lists allow item assignment, tuples might allow it under certain conditions, such as matching types or automatic conversion.

396
MCQhard

Given the code: x = 10; y = 3.0; z = x / y; print(type(z)). What is the output?

A.<class 'str'>
B.<class 'float'>
C.<class 'complex'>
D.<class 'int'>
AnswerB

Dividing an integer by a float in Python always yields a float, because the true division operator promotes the result to the wider numeric type. Here 10 / 3.0 evaluates to 3.333..., so type(z) returns <class 'float'>, satisfying the stem's request for the printed type.

Why this answer

In Python, when you divide an integer by a float using the / operator, the result is always a float. Here, x is an integer (10) and y is a float (3.0), so z = 10 / 3.0 evaluates to 3.3333333333333335, which is of type float. The print(type(z)) outputs <class 'float'>, making option B correct.

Exam trap

Python Institute often tests the distinction between / (true division) and // (floor division), trapping candidates who mistakenly think dividing an integer by a float returns an integer or that the result type depends on exact divisibility.

How to eliminate wrong answers

Option A is wrong because the result of division is a numeric type, not a string; <class 'str'> would only appear if the variable were explicitly assigned a string value. Option C is wrong because a complex number requires an imaginary part (e.g., 3+2j), and dividing an int by a float never produces a complex type. Option D is wrong because the / operator always returns a float in Python 3, even if the division is exact (e.g., 10 / 2.0 returns 5.0 as a float); integer division requires the // operator.

397
MCQeasy

What is the output of the following code? print('Hello'.upper())

A.hello
B.HELLO!
C.HELLO
D.Hello
AnswerC

The `upper()` string method returns a copy of the string with all cased characters converted to uppercase, leaving the original unchanged. Applied to `'Hello'`, it transforms each lowercase letter, producing `HELLO`. This satisfies the stem's requirement to determine the exact printed output of the expression.

Why this answer

The `.upper()` string method in Python returns a new string with all lowercase letters converted to uppercase. The string `'Hello'` contains the characters 'H', 'e', 'l', 'l', 'o'; after applying `.upper()`, it becomes `'HELLO'`. The output is exactly `HELLO` without any additional characters.

Exam trap

The PCEP exam often tests whether candidates understand that `.upper()` does not add or remove characters—it only changes the case of alphabetic characters, so any extra punctuation or unchanged casing indicates a misunderstanding of the method's exact behavior.

How to eliminate wrong answers

Option A is wrong because it shows the string in lowercase (`hello`), which would result from the `.lower()` method, not `.upper()`. Option B is wrong because it appends an exclamation mark (`HELLO!`), which is not part of the original string and is not added by the `.upper()` method. Option D is wrong because it shows the original mixed-case string (`Hello`), which would be the output if no method were called or if the method had no effect, but `.upper()` actively transforms the case.

398
MCQeasy

Which of the following is a floating-point literal?

A.'3.14'
B.42
C.1+2j
D.3.14
AnswerD

The decimal point makes 3.14 a floating-point literal, satisfying the stem's requirement for a real-number constant. Python's tokeniser classifies any numeric literal containing a decimal point or exponent as float, so 3.14 evaluates to type float rather than int. Integers such as 42 lack that fractional marker.

Why this answer

`3.14` is a numeric literal with a decimal point, which Python interprets as a floating-point number. Floating-point literals represent real numbers and can be written with a decimal point or using scientific notation (e.g., `3.14e0`).

Exam trap

The trap here is that candidates may confuse a string containing a number (like `'3.14'`) with an actual numeric literal, or mistake an integer literal for a float, especially when the number looks like a decimal but lacks the decimal point.

How to eliminate wrong answers

Option A is wrong because `'3.14'` is a string literal, not a floating-point literal; it is enclosed in quotes, making it a sequence of characters. Option B is wrong because `42` is an integer literal, which represents a whole number without a decimal point. Option C is wrong because `1+2j` is a complex number literal (with a real part `1` and an imaginary part `2j`), not a floating-point literal.

399
MCQhard

A log file processing script uses a while loop to read lines until a specific pattern is found. The code currently hangs. The developer suspects an infinite loop. Which change is most likely to fix the issue?

A.Add a break statement after reading the line
B.Increase the sleep time in the loop
C.Replace while with for loop
D.Ensure the condition variable is updated inside the loop
AnswerD

An infinite while loop typically occurs when the controlling condition variable never changes, so the exit condition is never met. Updating that variable inside the loop body ensures the condition eventually becomes false, allowing termination.

Why this answer

An infinite while loop typically occurs when the condition controlling the loop never becomes false. In a log file processing script, the condition variable (e.g., a line counter or a flag indicating the pattern was found) must be updated inside the loop body. Without that update, the loop condition remains true indefinitely, causing the hang.

Adding a `break` statement (option A) would exit the loop unconditionally after the first iteration, which is not the intended fix for a missing update.

Exam trap

Python Institute often tests the misconception that adding a `break` statement is the universal fix for infinite loops, when in fact the root cause is usually a missing update to the loop condition variable, not the absence of an explicit exit command.

How to eliminate wrong answers

Option A is wrong because adding a `break` statement after reading the line would exit the loop immediately after the first iteration, regardless of whether the pattern was found, which is not the intended behavior for processing until a specific pattern is found. Option B is wrong because increasing the sleep time only delays each iteration but does not change the loop condition; the loop would still run forever, just slower. Option C is wrong because replacing `while` with `for` does not inherently fix an infinite loop; if the condition variable is not updated, a `for` loop over a fixed range would terminate, but the problem specifically describes a `while` loop that hangs due to a condition that never becomes false, and a `for` loop would not match the requirement of reading until a pattern is found (it would iterate a fixed number of times).

400
MCQeasy

A junior developer writes the following code to swap two variables: a = 5; b = 10; a = b; b = a. When they print a and b, what is the output?

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

The first assignment a = b overwrites a with 10, destroying the original 5. The second assignment b = a then copies 10 back into b, so both variables hold 10; no temporary variable preserved the original value.

Why this answer

After `a = b`, both variables hold the value 10. Then `b = a` assigns the current value of `a` (which is now 10) to `b`, so both remain 10. The original value of `a` (5) is lost because it was overwritten before being saved.

Exam trap

The PCEP exam often tests the misconception that `b = a` after `a = b` somehow retrieves the original value of `a`, when in fact the original value is already overwritten.

How to eliminate wrong answers

Option B is wrong because it suggests both variables become 5, but `a = b` overwrites `a` with 10, so `a` cannot be 5. Option C is wrong because it implies the original values are preserved, but the assignment `a = b` destroys the original 5. Option D is wrong because it shows a correct swap, but the code does not use a temporary variable; the second assignment `b = a` uses the already-overwritten value of `a`, so `b` never receives the original 5.

401
MCQmedium

A student is writing a program that stores the daily steps walked over a week in a list. She wants to determine whether any day had fewer than 1000 steps, and if so, report the first such day's index. Which approach correctly finds the index of the first value below 1000?

A.Use a while loop with a counter that increments only when the step count is below 1000.
B.Use a for loop with range(len(steps)) and break when steps[i] < 1000, then use the loop variable i.
C.Use a for loop over the list elements and break when the element is below 1000, then print the element itself.
D.Use steps.index(min(steps)) to locate the day with the fewest steps.
AnswerB

Iterating with range(len(steps)) gives access to each valid index. When the condition steps[i] < 1000 becomes true, break exits immediately, and the loop variable i still holds the index of that first qualifying day. This is the standard manual-search pattern and correctly reports the earliest index without scanning further elements.

Why this answer

Finding the first element that satisfies a condition requires both the element and its position. Iterating over indices with range(len(steps)) provides the index, and breaking on the first match leaves the loop variable holding that index. Searching for the minimum, iterating over values, or counting qualifying days all answer different questions and cannot report the earliest qualifying index.

Exam trap

The trap here is using a search that finds the smallest value or counts matches, when the requirement is specifically the first position that crosses a threshold.

402
MCQhard

A developer is debugging a script that uses a `while` loop to process items from a queue. The loop is intended to run until the queue is empty, but the script hangs indefinitely. Which of the following is the most likely cause?

A.The `break` statement is missing from the loop body.
B.The loop uses `continue` instead of `break`.
C.The loop condition never becomes false because the queue is not being modified inside the loop.
D.The queue is a list, and lists cannot be used in `while` conditions.
AnswerC

If the queue is not modified within the loop (e.g., items are not removed), the condition `while queue:` remains true forever, causing an infinite loop. The loop must include an operation that eventually makes the condition false, such as `queue.pop()` or `queue.popleft()`, to terminate.

Why this answer

An infinite `while` loop occurs when the loop condition never evaluates to false. If the queue is not being emptied, the condition `while queue:` remains true. The loop body must include an operation that removes items from the queue, such as `pop()` or `popleft()`, to eventually make the condition false and terminate the loop.

Exam trap

The trap here is assuming that a `break` statement is necessary to exit a `while` loop, when actually the loop condition must become false.

403
MCQeasy

A developer wants to create a list of even numbers from 0 to 10 inclusive. Which code snippet will correctly produce [0, 2, 4, 6, 8, 10]?

A.list(range(0,11,2))
B.[x for x in range(11) if x%2==0]
C.[x*2 for x in range(6)]
D.All of the above
AnswerD

All three snippets produce the same list.

Why this answer

All three code snippets produce the list [0, 2, 4, 6, 8, 10]. Option A uses the built-in `range()` function with a step of 2, starting at 0 and stopping before 11. Option B is a list comprehension that iterates over range(11) and filters numbers where the remainder when divided by 2 is 0.

Option C multiplies each integer from 0 to 5 by 2, yielding the same even numbers. Therefore, D is correct.

Exam trap

The PCEP exam often tests whether candidates recognize that multiple approaches can produce the same correct result, and the trap here is that a student might dismiss Option C because it uses multiplication instead of a step or filter, not realizing it still yields the exact target list.

How to eliminate wrong answers

Option A is not wrong; it correctly produces the list. Option B is not wrong; it correctly uses a conditional filter to select even numbers. Option C is not wrong; it correctly generates even numbers by doubling each element in range(6).

Since all options are correct, the answer is D.

404
MCQeasy

Which keyword is used to define a function in Python?

A.def
B.func
C.function
D.define
AnswerA

The `def` keyword introduces a function definition, binding the function name to a callable object at runtime. It satisfies the stem's requirement for the specific keyword that declares functions, unlike `lambda` (anonymous expressions) or `class` (type definitions). Every named function in Python begins with `def`, followed by the name and parameter list.

Why this answer

In Python, the `def` keyword is used to define a function, followed by the function name, parentheses, and a colon. This is a fundamental syntax rule in the Python language specification, and no other keyword or identifier is valid for this purpose.

Exam trap

The PCEP exam often tests that candidates know `def` is the only correct keyword, while distractors like `function` (used in JavaScript) or `define` (a generic term) exploit confusion with other programming languages or natural language.

How to eliminate wrong answers

Option B is wrong because `func` is not a reserved keyword in Python; it is simply an identifier that could be used as a function name, but not to define a function. Option C is wrong because `function` is not a keyword in Python; it is a common term in other languages like JavaScript but has no special meaning in Python. Option D is wrong because `define` is not a Python keyword; it is a generic English word and would cause a syntax error if used in place of `def`.

405
MCQmedium

A developer is writing a Python script that stores the number of active user sessions in a variable. They want the variable to hold the value 42 as an integer. Which of the following statements correctly assigns the integer 42 to a variable named session_count?

A.session_count = 42
B.session_count := 42
C.session_count = '42'
D.int session_count = 42
AnswerA

This assignment uses the equals sign to bind the integer literal 42 to the name session_count. In Python, variables are created on assignment; no type declaration is needed. The value is stored as an int because 42 has no decimal point or quotes, making this the correct way to store the integer.

Why this answer

The correct assignment uses the equals sign to bind the integer literal to the variable name. Python does not require type declarations, and the absence of quotes ensures the value is an int. The other options either create a string, use invalid syntax, or misuse an operator not intended for simple assignment.

Exam trap

The trap here is confusing string literals with numeric literals because they look similar when printed, and forgetting that Python does not use C-style type declarations.

406
MCQmedium

A Python developer writes the following code to concatenate two strings: first = 'Hello' second = 'World' result = first + ' ' + second print(result) What is the output?

A.Hello World
B.HelloWorld
C.'Hello' 'World'
D.Error: cannot concatenate str and int
AnswerA

The + operator concatenates strings. The expression first + ' ' + second combines 'Hello', a space, and 'World', resulting in 'Hello World'. The space is explicitly added as a string literal. Therefore, the print statement outputs 'Hello World' with a space between the words. This is the correct result.

Why this answer

The + operator concatenates strings when both operands are strings. Here, first is 'Hello', then a space string ' ', then second is 'World'. The result is 'Hello World'.

The other options either omit the space, include quotes, or predict an error that does not occur because all operands are strings.

Exam trap

The trap here is forgetting that the space is explicitly included as a separate string, leading to the assumption that the output would be 'HelloWorld' without a space.

407
MCQhard

A developer writes: try: x = int('hello') except ValueError: x = 0 except TypeError: x = -1 finally: x = x + 1 What is the final value of x?

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

Converting `'hello'` raises `ValueError`, so the handler sets x to 0. The `TypeError` clause never executes. The `finally` block always runs, adding 1, giving x = 1. This satisfies the stem's requirement to trace exception handling and finalisation order precisely.

Why this answer

The code attempts to convert the string 'hello' to an integer, which raises a ValueError. The except ValueError block catches this and sets x = 0. The finally block always executes, adding 1 to x, so x becomes 1.

The TypeError except is never triggered because the error is a ValueError, not a TypeError.

Exam trap

The PCEP exam often tests the misconception that the finally block does not execute when an exception is caught, or that the exception type might be misidentified, leading candidates to pick the value from an unexecuted except clause.

How to eliminate wrong answers

Option A is wrong because it assumes the finally block does not execute or that x remains 0, but finally always runs and increments x to 1. Option C is wrong because it assumes a TypeError is raised and x becomes -1, but the actual exception is ValueError, not TypeError. Option D is wrong because it assumes the except block sets x to 0 and then finally adds 1 to get 1, not 2; there is no second increment.

408
MCQmedium

A program uses a while loop to find the largest number in a list until a negative number is encountered. What is wrong with this code? numbers = [3, 7, 2, -1, 5] max_num = 0 i = 0 while numbers[i] >= 0: if numbers[i] > max_num: max_num = numbers[i] i += 1 print(max_num)

A.The loop should start with max_num = None.
B.The loop should check all numbers until end of list.
C.The loop should continue even when number is negative (skip negatives).
D.The loop should use a for loop instead.
AnswerC

This is correct. The loop condition should not filter out negatives; instead, it should iterate through the entire list using an index check (e.g., i < len(numbers)), and inside the loop, skip negative numbers with an if statement. This ensures all numbers are considered for finding the largest non-negative number.

Why this answer

The while loop condition `numbers[i] >= 0` causes the loop to terminate as soon as it encounters a negative number (-1), so it never processes the number 5 at the end of the list. The intended behavior is to skip negative numbers and continue iterating through the entire list to find the largest number among all non-negative values. To fix this, the loop should use a condition that checks the index against the list length (e.g., `i < len(numbers)`) and then skip negative numbers with an `if` statement inside the loop.

Exam trap

Python Institute often tests the misconception that a while loop's condition should mirror the data filter (e.g., 'continue while number is non-negative'), when in reality the condition should control the iteration range (e.g., index within bounds) and the filter should be an inner `if` statement.

How to eliminate wrong answers

Option A is wrong because initializing `max_num` to `None` would cause a `TypeError` when comparing with an integer using `>` (e.g., `None > 3` is not valid in Python 3). Option B is wrong because the loop does not check all numbers until the end of the list; it stops early due to the negative number condition, but the core issue is the loop's termination condition, not the lack of a full traversal. Option D is wrong because a `for` loop would not inherently fix the problem; the same flawed logic (stopping at a negative number) could be replicated with a `for` loop if a `break` is used, and the question asks specifically about the while loop's logic error.

409
MCQeasy

What is the result of 17 % 5 in Python?

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

The modulo operator returns the remainder after integer division, so 17 % 5 evaluates to 2 because 5 divides into 17 three times (15) with 2 left over. This satisfies the stem's requirement for the exact result of the expression, matching Python's behaviour for positive integers.

Why this answer

In Python, the % operator performs modulo division, returning the remainder after integer division. 17 divided by 5 equals 3 with a remainder of 2 (since 5 * 3 = 15, and 17 - 15 = 2), so 17 % 5 evaluates to 2.

Exam trap

Python Institute often tests the distinction between the modulo operator (%) and floor division (//), trapping candidates who confuse the remainder with the quotient.

How to eliminate wrong answers

Option B (4) is wrong because it incorrectly assumes the result is the quotient minus 1, or confuses modulo with floor division (17 // 5 = 3). Option C (3) is wrong because it represents the integer quotient (17 // 5), not the remainder. Option D (1) is wrong because it might come from mistakenly subtracting 5 twice (17 - 5 - 5 = 7, then 7 - 5 = 2, not 1) or from a miscalculation of the remainder.

410
MCQeasy

A support technician is running a Python script that parses a configuration file and stores key-value pairs in a dictionary called 'config'. The script then uses these values to set application parameters. The configuration file is optional, and some expected keys may be missing. Currently, the script crashes with a KeyError when accessing a missing key. The technician needs to modify the script to safely retrieve a value or return 'N/A' if a key is missing. The script must remain efficient and readable. Which modification best achieves this?

A.Use config.get(key, 'N/A') instead of direct key access
B.Wrap each access in a try-except block to catch KeyError and assign 'N/A'
C.Use if key in config: value = config[key] else: value = 'N/A'
D.Use config.setdefault(key, 'N/A') before accessing
AnswerA

Using `config.get(key, 'N/A')` returns the supplied default when the key is absent, so no KeyError is raised. This satisfies the requirement to retrieve a value or fall back to 'N/A' for missing optional keys, while keeping the lookup a single, readable expression rather than a multi-line membership test.

Why this answer

`dict.get(key, default)` is the idiomatic Python method for safely retrieving a value from a dictionary without raising a `KeyError`. It returns the default value `'N/A'` when the key is missing, which directly solves the crash while keeping the code concise and readable. This approach is more efficient than exception handling or explicit membership checks because it performs a single hash lookup.

Exam trap

The PCEP exam often tests the distinction between `dict.get()` and `dict.setdefault()`, trapping candidates who think `setdefault()` is a safe retrieval method without realizing it permanently modifies the dictionary by adding the missing key.

How to eliminate wrong answers

Option B is wrong because wrapping each access in a try-except block is verbose, less readable, and slower than using `.get()` due to the overhead of exception handling; it also violates Python's EAFP (Easier to Ask for Forgiveness than Permission) principle in a case where a simple method exists. Option C is wrong because using `if key in config:` performs two dictionary lookups (one for the membership test and one for the retrieval), which is less efficient and more verbose than the single lookup in `.get()`. Option D is wrong because `config.setdefault(key, 'N/A')` modifies the dictionary by inserting the key with the default value if it is missing, which is not the intended behavior—the script should only retrieve a value or return 'N/A' without altering the original dictionary.

411
MCQhard

What is the output of the following code? try: print(1/0); except ZeroDivisionError: print('error'); finally: print('done')

A.error done
B.error
C.done error
D.1/0 done
AnswerA

Dividing by zero raises ZeroDivisionError, caught by the except block, which prints 'error'. The finally block always executes regardless of exception handling, printing 'done'. This satisfies the stem's requirement to show both the handled exception output and the guaranteed finally output.

Why this answer

The code attempts to divide 1 by 0, which raises a ZeroDivisionError. The except block catches this specific exception and prints 'error', then the finally block always executes, printing 'done'. The output is therefore 'error' followed by 'done' on separate lines.

Exam trap

The PCEP exam often tests the mandatory execution order of the finally block, tricking candidates into thinking it only runs when no exception occurs or that it runs before the except block.

How to eliminate wrong answers

Option B is wrong because it omits the 'done' output from the finally block, which always executes regardless of whether an exception occurs. Option C is wrong because it reverses the order of output; the except block runs before the finally block, so 'error' must come before 'done'. Option D is wrong because it incorrectly shows the literal expression '1/0' as output, but the code never prints that expression; it only prints the strings 'error' and 'done'.

412
MCQeasy

A developer needs to store configuration settings as key-value pairs and later retrieve the value for a key that may not exist, providing a default value if the key is missing. Which dictionary method should be used?

A.get()
B.pop()
C.keys()
D.setdefault()
AnswerA

The get() method returns the value for a given key if it exists, otherwise it returns a specified default value (or None if no default is provided). It does not raise an exception for missing keys, making it ideal for this scenario.

Why this answer

The get() method safely retrieves a value for a key and returns a default if the key is absent, without altering the dictionary. Other methods either modify the dictionary or do not directly retrieve values, making them unsuitable for a read-only lookup with a fallback.

Exam trap

The trap here is assuming that setdefault() is equivalent to get() for retrieval, ignoring that setdefault() inserts the missing key into the dictionary, which may cause unintended side effects.

413
MCQmedium

A developer wants to output a variable price with two decimal places using formatting. Which line of code will produce 'Price: $12.50' for price = 12.5?

A.print('Price: $' + price)
B.print(f'Price: ${price:.2f}')
C.print('Price: $' + str(round(price, 2)))
D.print('Price: $%s' % price)
AnswerB

The f-string's `:.2f` format specifier rounds the float to exactly two decimal places, satisfying the stem's two-decimal requirement. Substituting price = 12.5 yields `12.50`, and the literal `$` inside the string produces the required `Price: $12.50` output precisely.

Why this answer

It uses an f-string with the format specifier `:.2f`, which formats the float `12.5` as a string with exactly two decimal places, producing '12.50'. The f-string then interpolates this into the full string 'Price: $12.50'.

Exam trap

Python Institute often tests the difference between `round()` (which returns a float and may not add trailing zeros) and format specifiers (which control string representation), leading candidates to mistakenly choose Option C thinking it produces two decimal places.

How to eliminate wrong answers

Option A is wrong because it attempts to concatenate a string with a float using the `+` operator, which raises a `TypeError` (cannot concatenate str and float). Option C is wrong because `round(price, 2)` returns the float `12.5` (not a string), and converting it with `str()` yields '12.5' without forcing two decimal places, so the output would be 'Price: $12.5'. Option D is wrong because the `%s` placeholder converts the float to a string using `str()`, which again produces '12.5' without two decimal places, and the `%` formatting does not apply numeric precision to `%s`.

414
MCQhard

A programmer is debugging a Python script that uses a while loop to process a list of numbers. The code is: numbers = [1, 2, 3, 4, 5] i = 0 while i < len(numbers): if numbers[i] % 2 == 0: print(numbers[i]) i += 1 What is the output of this code?

A.2 4 6
B.An infinite loop occurs because i is not incremented.
C.1 3 5
D.2 4
AnswerD

The loop iterates over the list using index i from 0 to 4. The condition checks if the current number is even (numbers[i] % 2 == 0). For 1, it's odd (no print). For 2, it's even (print 2). For 3, odd. For 4, even (print 4). For 5, odd. So the output is 2 and 4 on separate lines. The loop increments i correctly, avoiding an infinite loop.

Why this answer

The while loop iterates through the list by index, checking each element for evenness using the modulo operator. When an even number is found, it is printed. The loop correctly increments the index, so it terminates after processing all elements.

The even numbers in the list are 2 and 4, so they are printed on separate lines.

Exam trap

The trap here is misreading the modulo condition and thinking it prints odd numbers, or overlooking the increment that prevents an infinite loop.

415
Multi-Selectmedium

A developer is reviewing loop constructs that iterate over the list scores = [10, 20, 30]. Which two statements about iterating this list are true? (Choose two.)

Select 2 answers
A.for s in scores: assigns s to each index position, so s holds 0, 1, and 2 during iteration.
B.for s in scores: accesses each element value directly, so s takes the values 10, 20, and 30 in order.
C.for i in range(len(scores)): gives i the values 0, 1, and 2, which can be used to index scores.
D.Modifying scores by appending a new element during a for loop over scores reliably processes the appended element in the same loop.
E.A for loop over scores always executes at least once, even when the list is empty.
AnswersB, C

Iterating a list directly yields its elements, so the loop variable receives 10, then 20, then 30. This is the most direct way to read values when the positions are not needed. The list itself is not modified, and the order follows the list's internal sequence, which here matches the order in which the values were written.

Why this answer

Python lets you iterate a list either by value, where the loop variable receives each element, or by index, where a range over the list's length supplies positions usable with subscripting. Direct value iteration is simplest for reading data, while index iteration is needed when positions matter. Appending during iteration is unreliable, and an empty list produces no iterations.

Exam trap

The trap here is assuming a plain for loop over a list provides indices, when it actually yields element values.

416
MCQmedium

A developer defines a function with the signature def configure(host, port=8080, protocol='http'). A call is made as configure('web01', protocol='https'). Which statement describes what happens?

A.The call fails with a SyntaxError because default parameters must always be passed explicitly when any keyword argument is used.
B.The call succeeds; host receives 'web01', port keeps its default 8080, and protocol receives 'https'.
C.The call fails with a TypeError because a positional argument cannot be combined with a keyword argument.
D.The call succeeds, but 'https' is assigned to port because keyword arguments fill parameters in declaration order.
AnswerB

Positional arguments fill parameters left to right, so 'web01' binds to host. The keyword argument protocol='https' binds by name, skipping port, which therefore retains its default value of 8080. Python allows mixing positional and keyword arguments as long as no parameter receives two values and no required parameter is missing, so this call is valid and behaves exactly as described.

Why this answer

Positional arguments bind to parameters in order, while keyword arguments bind by name regardless of position. Here the single positional value fills host, the keyword protocol fills that named parameter, and port is simply omitted, so it retains its default. The call is valid and produces host='web01', port=8080, protocol='https'.

Exam trap

The trap here is thinking keyword arguments are matched to parameters by their left-to-right position in the call rather than by their explicit names.

417
MCQeasy

What does 'print(2 ** 3)' output?

A.9
B.23
C.8
D.6
AnswerC

The `**` operator performs exponentiation, raising the left operand to the power of the right. Here 2 raised to the power 3 equals 8, so `print` outputs 8. It is distinct from `^`, which is bitwise XOR in Python.

Why this answer

The ** operator in Python performs exponentiation, raising the left operand (2) to the power of the right operand (3), which equals 8. The print() function then outputs this integer result to the console.

Exam trap

The trap here is that candidates often confuse the ** operator with multiplication (*) or addition (+), leading them to pick 6 or 23, or they reverse the base and exponent, picking 9 instead of 8.

How to eliminate wrong answers

Option A is wrong because 9 would be the result of 3 ** 2 (3 squared), not 2 ** 3; this confuses the base and exponent. Option B is wrong because 23 is the result of string concatenation '2' + '3', not the exponentiation operator; this confuses the ** operator with string operations. Option D is wrong because 6 is the result of 2 * 3 (multiplication), not 2 ** 3 (exponentiation); this confuses the ** operator with the * multiplication operator.

418
MCQhard

A data analyst is processing a large dataset of customer transactions. The dataset is stored as a list of dictionaries, each with keys 'amount' and 'date'. The analyst needs to compute the total revenue for 2024. They write: total = 0 for t in transactions: if t['date'].year == 2024: total += t['amount'] They then run it and get a KeyError: 'date'. After inspection, they notice that some records have a 'Date' key (capital D) instead. The analyst wants to fix this without modifying the data. Which approach will correctly sum amounts regardless of key case?

A.Change the if condition to: if t.get('date', t.get('Date')).year == 2024
B.Use a try-except block to catch KeyError and use alternative key
C.Convert all keys to lowercase before processing
D.Use a list comprehension with conditional chaining
AnswerA

Correct: get with fallback handles both key casings.

Why this answer

`dict.get(key, default)` safely attempts to retrieve the value for 'date', and if that key is missing, it falls back to retrieving the value for 'Date'. This handles the case inconsistency without modifying the original data and avoids a KeyError. The `.year` attribute is then accessed on the returned date object.

Exam trap

Python Institute often tests the distinction between direct key access (`dict[key]`) which raises KeyError, and the safer `dict.get()` method, and the trap here is that candidates may think a try-except block is the only way to handle missing keys, overlooking the more Pythonic and concise `.get()` with a fallback.

How to eliminate wrong answers

Option B is wrong because a try-except block would work but is less Pythonic and less efficient than using `.get()` with a fallback; it also requires an extra nested block and is not the simplest fix. Option C is wrong because converting all keys to lowercase would require modifying the data (e.g., creating new dictionaries), which violates the requirement 'without modifying the data'. Option D is wrong because a list comprehension with conditional chaining does not directly solve the key-case issue; it would still need a way to handle the missing key, and chaining conditions like `if t.get('date', t.get('Date')).year == 2024` is essentially the same as option A but in a comprehension, not a fundamentally different approach.

419
Drag & Dropmedium

Arrange the steps to slice a list in Python.

Drag or tap steps into the slots.

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

Why this order

List slicing in Python uses the syntax [start:stop:step] within square brackets on an existing list. The correct order is to first have the list, then define the start index, then the stop index, and finally an optional step. Common mistakes include putting indices out of order or attempting to slice before the list exists.

420
MCQhard

Consider the following code: `x = 5` then `y = 2` then `result = x // y * y + x % y`. What is the value of `result`?

A.`7`
B.`6`
C.`5`
D.`2`
AnswerC

Operator precedence: `//`, `*`, and `%` have the same precedence and are evaluated left-to-right. First `x // y` gives `2` (since `5 // 2 = 2`). Then `2 * y` gives `4`. Then `x % y` gives `1` (since `5 % 2 = 1`). Finally, `4 + 1` equals `5`. This is a standard identity: `(x // y) * y + (x % y)` reconstructs `x` for positive integers.

Why this answer

The expression combines floor division, multiplication, and modulo. Due to left-to-right evaluation of operators with equal precedence, `x // y` is computed first, then multiplied by `y`, then `x % y` is computed and added. For `x = 5` and `y = 2`, this yields `(5 // 2) * 2 + (5 % 2) = 2 * 2 + 1 = 5`.

This demonstrates the relationship between floor division and modulo.

Exam trap

The trap here is misapplying operator precedence, such as evaluating `*` before `//` or `%`, or misunderstanding the modulo operation.

421
MCQmedium

A developer wants to assign the value 3.14 to a variable and later change it to the integer 3. Which of the following is true?

A.This is allowed only if the variable was declared as a float.
B.This causes a TypeError because you cannot change types.
C.This is allowed because Python is dynamically typed.
D.This is allowed only if you use the int() function during assignment.
AnswerC

Python variables are unbound names, so rebinding `pi` from the float 3.14 to the integer 3 is legal; the interpreter checks types at runtime, not at declaration. This satisfies the stem's requirement that the same name later hold a different type, which dynamic typing permits.

Why this answer

Python is dynamically typed, meaning variables can be reassigned to values of any type at runtime. The developer can first assign the float 3.14 to a variable and later reassign the integer 3 to the same variable without any type declaration or conversion function required.

Exam trap

The trap here is that candidates often confuse Python's dynamic typing with static typing rules from languages like Java or C, leading them to believe that type changes require explicit conversion or are disallowed.

How to eliminate wrong answers

Option A is wrong because Python does not require variable declaration with a type; you can assign any value to any variable regardless of its previous type. Option B is wrong because Python does not raise a TypeError when changing the type of a variable; dynamic typing allows reassignment to a different type without error. Option D is wrong because the int() function is not required for reassignment; you can directly assign the integer 3 without any conversion.

422
MCQhard

A script runs: x = 5 y = x y += 3 print(x, y) What is printed?

A.5 8
B.5 5
C.8 5
D.8 8
AnswerA

After y = x, both names refer to the same integer object with value 5. The statement y += 3 computes 5 + 3 and rebinds y to a new integer object with value 8, but it does not modify the original object, which integers cannot do. The name x still references 5, so the script prints 5 8.

Why this answer

Names in Python are references to objects, and integers are immutable. Assigning y = x makes both names point to the same 5 object, but y += 3 creates a new integer and rebinds only y. Since x is never reassigned, it continues to reference 5, and the output is 5 8.

Exam trap

The trap here is believing that assigning one variable to another creates a permanent link, so changing one automatically changes the other.

423
MCQhard

A Python programmer writes the following code: x = 5 y = 2 result = x / y print(type(result)) What is printed?

A.<class 'int'>
B.<class 'decimal'>
C.<class 'float'>
D.<class 'double'>
AnswerC

In Python 3, the division operator / always returns a floating-point number, even when both operands are integers and the division is exact. Here, 5 / 2 yields 2.5, which is a float. The type() function returns <class 'float'>.

Why this answer

In Python 3, the division operator / performs true division and always returns a float, even if the result is a whole number. Therefore, 5 / 2 evaluates to 2.5, and type(result) is <class 'float'>. The floor division operator // would return an integer if both operands are integers.

Exam trap

The trap here is assuming that division of two integers yields an integer, as in Python 2 or some other languages, when Python 3 always returns a float for /.

424
Multi-Selectmedium

Which of the following expressions evaluate to True? (Choose three.)

Select 3 answers
A.3 ** 2 == 9
B.4.0 == 4
C.10 % 3 == 0
D."Py" in "Python"
E.bool(0)
AnswersA, B, D

Raising 3 to the power of 2 via the exponentiation operator yields 9, so the equality comparison returns True. This satisfies the stem's requirement for expressions evaluating to True, since Python's ** operator binds tighter than ==, making the comparison 9 == 9.

Why this answer

Option A is correct because the exponentiation operator ** raises 3 to the power of 2, yielding 9, and 9 == 9 evaluates to True. Option B is correct because in Python, comparing a float and an int with == performs numeric value comparison: 4.0 and 4 represent the same numeric value, so 4.0 == 4 is True. Option D is correct because the in operator performs a substring membership test on strings, and the substring "Py" occurs at the start of "Python", so the expression is True.

Option C is not correct because 10 % 3 returns the remainder 1 (not 0), so 1 == 0 is False. Option E is not correct because bool(0) evaluates to False, not True, since zero is a falsy value in Python.

Exam trap

The PCEP exam often tests the distinction between the modulo operator returning the remainder (not the quotient) and the falsy nature of zero, leading candidates to mistakenly think `10 % 3 == 0` or `bool(0)` evaluate to `True`.

425
MCQeasy

What is the type of the result of the expression 5 + 3.0?

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

Adding an int and a float triggers Python's implicit numeric promotion: the int operand is converted to float before addition, so the result always takes the wider type. Here 5 becomes 5.0, and 5.0 + 3.0 yields 8.0, a float, satisfying the expression's mixed-type operand constraint.

Why this answer

In Python, when an integer (int) and a float are combined using the addition operator, the result is implicitly converted to a float to preserve precision. Since 3.0 is a float, 5 + 3.0 yields 8.0, which is of type float.

Exam trap

The PCEP exam often tests the misconception that adding an integer and a float returns an integer, or that Python truncates the result, when in fact Python always promotes to the more precise type (float).

How to eliminate wrong answers

Option A is wrong because str is the string type, and adding an int and a float does not produce a string unless explicit conversion is performed. Option C is wrong because int would only result if both operands were integers; the presence of 3.0 forces implicit conversion to float. Option D is wrong because complex numbers require a real and imaginary part (e.g., 5+3j), and this expression involves no imaginary component.

426
MCQmedium

Given the code: ```python name = input('Enter your name: ') print('Hello, ' + name) ``` If the user enters 'Alice', what is the output?

A.Hello,Alice
B.Hello, 'Alice'
C.Hello, Alice
D.Hello, Alice
AnswerC

The `input()` function returns the entered text as a string, so `name` holds `'Alice'`. String concatenation with `+` joins `'Hello, '` and `'Alice'` into a single string, which `print()` outputs exactly as `Hello, Alice`, satisfying the stem's request for the program's output.

Why this answer

The `print('Hello, ' + name)` statement concatenates the string literal `'Hello, '` (which includes a trailing space) with the user input `'Alice'`, producing the output `Hello, Alice`. The `input()` function returns the exact string entered by the user without any extra quotes or formatting.

Exam trap

Python Institute often tests whether candidates notice the trailing space in the string literal `'Hello, '` versus a missing space, and whether they understand that `input()` does not add quotes around the entered value.

How to eliminate wrong answers

Option A is wrong because it omits the space between 'Hello,' and 'Alice', which is present in the code as part of the string literal `'Hello, '`. Option B is wrong because it incorrectly adds single quotes around the name, which are not part of the output; the `input()` function does not add quotes to the user's input. Option D is wrong because it is identical to option C, but the question expects a single correct answer; the duplication is a distractor, and the correct output is exactly `Hello, Alice` with a space.

427
MCQeasy

A Python program prompts the user for their age and stores it in a variable. Which is the correct way to convert the input to an integer?

A.age = str(input("Age: "))
B.age = float(input("Age: "))
C.age = input("Age: ")
D.age = int(input("Age: "))
AnswerD

input() always returns a string, so wrapping it in int() converts the typed characters into an integer before assignment. This satisfies the requirement to store age as a numeric type, enabling arithmetic rather than string concatenation or comparison failures.

Why this answer

The `input()` function in Python always returns a string, and to perform arithmetic operations or numeric comparisons, the string must be explicitly converted to an integer using the `int()` constructor. This is a fundamental requirement for type conversion in Python when handling user input.

Exam trap

The PCEP exam often tests the misconception that `input()` returns a numeric type, leading candidates to forget explicit type conversion and choose option C, which stores the input as a string and causes type-related errors in subsequent operations.

How to eliminate wrong answers

Option A is wrong because `str(input(...))` redundantly converts the already-string result of `input()` to a string, leaving the data type unchanged and still unsuitable for integer operations. Option B is wrong because `float(input(...))` converts the input to a floating-point number, which is not the correct type for an integer age and may introduce unnecessary decimal precision or rounding issues. Option C is wrong because `age = input("Age: ")` stores the input as a string, so any attempt to use `age` in arithmetic (e.g., `age + 1`) will raise a TypeError.

428
MCQmedium

A developer needs to swap the values of two variables a and b without using a temporary variable. Which single line of code correctly performs the swap?

A.a = b; b = a
B.a, b = b, a
C.a = a ^ b; b = a ^ b; a = a ^ b
D.a = a + b; b = a - b; a = a - b
AnswerB

Tuple packing and unpacking evaluates the right-hand side first, building the tuple (b, a), then assigns its elements to a and b. This swaps the values in one statement, satisfying the no-temporary-variable constraint in the stem.

Why this answer

Python supports tuple unpacking, which allows swapping the values of two variables in a single line without a temporary variable. The expression `a, b = b, a` evaluates the right-hand side tuple `(b, a)` first, then assigns the values to `a` and `b` respectively, effectively swapping them. Option A fails because after `a = b`, the original value of `a` is lost, so `b = a` assigns the same value to both.

Option C (XOR swap) works but requires three statements, not a single line. Option D (arithmetic swap) also works but requires three statements and may cause overflow in other languages, though Python handles big integers; still, it is not a single line.

Exam trap

Candidates may think that XOR or arithmetic swaps are acceptable, but they require multiple lines. The question explicitly asks for a 'single line of code', so only tuple unpacking qualifies.

How to eliminate wrong answers

Option A is wrong because `a = b; b = a` first overwrites `a` with `b`'s value, then assigns the now-overwritten `a` (which equals original `b`) to `b`, resulting in both variables holding the original `b` value, not a swap. Option C is wrong because it uses XOR bitwise operations across three lines, not a single line as required by the question. Option D is wrong because it uses arithmetic operations across three lines, not a single line as required by the question.

429
MCQeasy

A programmer is writing a function that accepts a dictionary of employee records and must return a tuple containing the number of records and the average salary. The function should not modify the input dictionary. Which function definition achieves this?

A.def summarize(employees): count = len(employees) total = sum(employees.keys()) return (count, total / count)
B.def summarize(employees): count = len(employees) total = sum(employees.values()) return (count, total / count)
C.def summarize(employees): count = len(employees) if count == 0: return (0, 0) total = sum(employees.values()) return (count, total / count)
D.def summarize(employees): count = len(employees) total = sum(employees.values()) employees.clear() return (count, total / count)
AnswerC

This function correctly returns a tuple of the number of records and the average salary, and it handles the empty dictionary case by returning (0, 0). It does not modify the input dictionary. The use of employees.values() assumes that the dictionary values are numeric salaries, which aligns with the scenario. This is the most robust and correct implementation.

Why this answer

The correct function must return a tuple with the count and average salary, avoid modifying the input, and handle an empty dictionary gracefully. The chosen option includes a check for zero count, returns a sensible default, and uses dictionary values for the salary sum. The others either fail on empty input, sum the wrong data, or mutate the input.

Exam trap

The trap here is overlooking the empty-dictionary case or accidentally summing keys instead of values, which are common mistakes when working with dictionaries.

430
Multi-Selectmedium

A developer is writing a function that accepts a variable number of arguments and needs to handle them as a tuple. Which two of the following statements about tuples and function arguments are true? (Choose two.)

Select 2 answers
A.Tuples are mutable, so the arguments collected by *args can be modified inside the function.
B.A tuple cannot be passed to a function as a single argument if the function expects multiple parameters.
C.Inside a function, the *args parameter collects extra positional arguments into a tuple.
D.A tuple can be unpacked into positional arguments when calling a function using the * operator.
E.The **kwargs parameter collects extra keyword arguments into a tuple.
AnswersC, D

When a function is defined with *args, any additional positional arguments passed to the function are gathered into a tuple named args. This allows the function to accept an arbitrary number of arguments. The tuple is immutable, so the collected arguments cannot be modified in place. This is a standard Python feature for flexible function signatures.

Why this answer

The *args parameter collects extra positional arguments into a tuple, and the * operator can unpack a tuple into positional arguments in a function call. These two features are often used together to create flexible functions. The **kwargs parameter collects keyword arguments into a dictionary, not a tuple, and tuples are immutable, so their contents cannot be changed.

Understanding these behaviors is essential for working with variable argument lists in Python.

Exam trap

The trap here is mixing up *args and **kwargs, or assuming that tuples are mutable and can be modified inside a function.

431
MCQeasy

What is the data type of z after executing z = 10 / 2?

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

The division operator always returns a float in Python 3, even when both operands are integers and divide evenly. So 10 / 2 yields 5.0, a float, not an int. This satisfies the question's requirement to identify the resulting data type.

Why this answer

Float because in Python, the / operator always performs true division and returns a float, regardless of the operands. This is a fundamental concept tested in the PCEP exam to distinguish between / and //.

Exam trap

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

How to eliminate wrong answers

Option A is wrong because bool is a subtype of int in Python, but the result of 10 / 3 is not a boolean value (True or False). Option B is wrong because int would be the result of floor division (10 // 3) or integer division in some languages, but Python's / operator always returns a float. Option D is wrong because str is a string type, and the division operator does not produce a string; it produces a numeric float.

432
Multi-Selectmedium

Which FOUR of the following are correct uses of the print() function?

Select 4 answers
A.print 'Hello'
B.print('Hello', 'World', sep='-')
C.print('Hello', 'World')
D.print('Hello')
E.print('Hello', 5)
AnswersB, C, D, E

Passing `sep='-'` overrides print()'s default single-space separator, so the two arguments are joined with a hyphen and the output is `Hello-World`. This satisfies the stem's requirement for a correct use of print(), since `sep` is a valid keyword argument controlling the separator inserted between multiple positional arguments.

Why this answer

Option B is correct because print() accepts the keyword argument sep to define the separator between multiple arguments, so print('Hello', 'World', sep='-') outputs Hello-World. Option C is correct because print() can take multiple positional arguments and by default separates them with a single space, producing Hello World. Option D is correct because print('Hello') is the standard way to call print() with a single string argument, outputting Hello followed by a newline.

Option E is correct because print() accepts arguments of different types, so print('Hello', 5) outputs Hello 5, converting the integer to its string representation. Option A is not correct because print 'Hello' is Python 2 statement syntax, not a valid call to the print() function in Python 3.

Exam trap

Python Institute often tests the distinction between Python 2's print statement (no parentheses) and Python 3's print function (requires parentheses), leading candidates to mistakenly select option A as valid.

433
Drag & Dropmedium

Order the steps to write a for loop that iterates over a range of numbers.

Drag or tap steps into the slots.

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

Why this order

The correct order is to write 'for', then the loop variable, then 'in', then the range() function with appropriate arguments, then a colon, and finally an indented block containing the statements to repeat. This structure defines a for loop that iterates over a sequence generated by range().

434
MCQeasy

A developer writes a function that needs to accept any number of positional arguments and return their sum. Which function definition correctly collects all positional arguments into a tuple named values?

A.def total(*values):
B.def total(**values):
C.def total(*values, **kwargs):
D.def total(values):
AnswerA

The *values parameter collects any number of positional arguments into a tuple named values. Inside the function, sum(values) can add them. This matches the scenario exactly: total(1, 2, 3) yields values as (1, 2, 3). It also allows zero arguments, in which case values is an empty tuple and sum returns 0.

Why this answer

The *args syntax in a function definition packs all positional arguments into a tuple. Using def total(*values) makes values a tuple containing every positional argument passed. Then sum(values) returns their total.

The other definitions either collect keyword arguments into a dictionary, accept only one argument, or add an unnecessary keyword-argument collector that changes the function's behavior.

Exam trap

The trap here is confusing *args and **kwargs, assuming that ** collects positional arguments into a tuple when it actually collects keyword arguments into a dictionary.

435
Multi-Selectmedium

A developer is reviewing Python's built-in numeric types while preparing a data-processing script. Which TWO statements about Python's numeric types are accurate? (Choose two.)

Select 2 answers
A.The int type can represent arbitrarily large whole numbers, limited only by available memory.
B.The float type stores values with exact decimal precision for all real numbers.
C.The bool type is a subclass of int, so True and False behave as 1 and 0 in arithmetic.
D.The complex type cannot be used with the addition operator.
E.Dividing two integers with the single slash operator always produces an integer result.
AnswersA, C

Python integers are arbitrary-precision objects, so values grow beyond the fixed widths found in many other languages. Computing large powers such as 2 ** 200 produces an exact integer rather than an overflow. This behavior makes int suitable for exact arithmetic in scripts that process large counts or identifiers, and it is a defining characteristic of the type.

Why this answer

Python's int objects use arbitrary precision, allowing whole numbers far larger than fixed-width machine integers, and bool is a subclass of int whose instances act as one and zero in arithmetic. Together these two facts describe genuine features of the numeric type hierarchy. The other statements mischaracterize floats as exact, deny arithmetic support for complex numbers, and confuse true division with floor division.

Exam trap

The trap here is assuming that all numeric types behave like fixed-width integers from other languages, which leads to wrongly accepting claims about float exactness or integer overflow.

436
MCQeasy

What does the following code output? try: x = int('abc') except ValueError: print('Invalid')

A.The program crashes
B.Invalid
C.(Nothing printed)
D.abc
AnswerB

Converting 'abc' with int() raises a ValueError, since the string holds no valid integer literal. The except clause names ValueError specifically, so it catches that exception and executes print('Invalid'). The try block aborts at the failing assignment, meaning nothing else runs before the handler outputs the required text.

Why this answer

The code attempts to convert the string 'abc' to an integer using int(). Since 'abc' is not a valid integer, Python raises a ValueError. The except block catches this specific exception and executes print('Invalid'), so the output is 'Invalid'.

Option B is correct because the exception is handled gracefully without crashing.

Exam trap

The PCEP exam often tests whether candidates understand that a caught exception does not crash the program; the trap here is that some candidates think any error causes a crash, but the except block prevents that.

How to eliminate wrong answers

Option A is wrong because the ValueError is explicitly caught by the except block, preventing the program from crashing; unhandled exceptions cause crashes, but here the exception is handled. Option C is wrong because the except block executes and prints 'Invalid', so something is printed. Option D is wrong because the code does not print the original string 'abc'; it prints the string 'Invalid' from the except block.

437
MCQmedium

A developer is inspecting a variable and writes: value = 7.0 // 2. What is the value and type of the result assigned to 'value'?

A.3.5, of type float
B.3, of type int
C.4.0, of type float
D.3.0, of type float
AnswerD

The floor division operator // divides and rounds down to the nearest integer value, but when either operand is a float the result is a float. 7.0 // 2 computes 3.5 and floors it to 3.0, keeping the float type. This is correct because // preserves float type when any operand is a float.

Why this answer

Floor division // computes the quotient and rounds down to the nearest whole number, and the result is a float whenever either operand is a float. With 7.0 // 2, the quotient 3.5 floors to 3.0 and remains a float. The int result appears only when both operands are ints, and plain division would leave 3.5.

Exam trap

The trap here is assuming // always returns an int, when in fact it returns a float if either operand is a float.

438
Multi-Selectmedium

A Python script performs the following operations: s = "Hello" n = 5 result1 = s * 2 result2 = s + str(n) Which TWO statements about the values of result1 and result2 are true? (Choose two.)

Select 2 answers
A.result1 is "HelloHello"
B.result1 is 10
C.result2 is "Hello5"
D.result2 causes a TypeError
E.result1 is "Hello Hello"
AnswersA, C

The multiplication operator on a string and an integer repeats the string. Here s * 2 concatenates two copies of "Hello", producing "HelloHello". This is a standard string operation in Python that does not modify the original string but returns a new one. The value assigned to result1 is therefore exactly "HelloHello".

Why this answer

String repetition with * produces a new string containing the original repeated the given number of times, so "Hello" * 2 yields "HelloHello". Concatenation with + requires both operands to be strings, so the integer must be converted using str before joining, producing "Hello5". Direct concatenation without conversion would raise a TypeError.

Exam trap

The trap here is assuming that string multiplication inserts separators or performs numeric multiplication, and forgetting that concatenation requires explicit type conversion.

439
Multi-Selectmedium

Which two of the following are correct ways to create a dictionary in Python? (Choose two.)

Select 2 answers
A.my_dict = {a:1, b:2}
B.my_dict = dict(a=1, b=2)
C.my_dict = dict(['a',1],['b',2])
D.my_dict = {'a':1, 'b':2}
E.my_dict = ["a":1, "b":2]
AnswersB, D

The dict() constructor accepts keyword arguments, mapping each parameter name to its value as a string key. This satisfies the requirement for a valid dictionary-creation syntax, producing {'a': 1, 'b': 2} without needing literal braces or quoted keys.

Why this answer

Option B, my_dict = dict(a=1, b=2), is correct because the dict() constructor accepts keyword arguments, using the parameter names as string keys and the assigned values as their values, producing {'a': 1, 'b': 2}. Option D, my_dict = {'a':1, 'b':2}, is correct because it uses standard dictionary literal syntax with curly braces, colon-separated key-value pairs, and comma separators. Option A is invalid because bare identifiers a and b are treated as variables rather than string keys, so it raises a NameError unless those variables exist, and even then it would not create the intended string-keyed dictionary.

Option C is invalid because dict() expects a single iterable of key-value pairs (e.g., dict([('a',1),('b',2)])), not multiple separate list arguments. Option E is invalid because square brackets denote a list, and the colon syntax inside them is not valid Python.

Exam trap

The PCEP exam often tests the distinction between valid dictionary creation syntax and common mistakes like missing quotes around keys, using wrong brackets, or misunderstanding how the `dict()` constructor accepts arguments.

440
Drag & Dropmedium

Arrange the steps to write and run a Python script from the command line in the correct order.

Drag or tap steps into the slots.

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

Why this order

The process involves creating the script, saving it, opening a terminal, navigating to its location, and executing it with the Python interpreter.

441
MCQmedium

A data scientist needs to read a list of floats from a file, one per line, and compute the sum. The current code: total = 0.0 with open("data.txt") as f: for line in f: total = total + line print(total) When run, a TypeError occurs: unsupported operand type(s) for +: 'float' and 'str'. The scientist knows that line is a string. Which fix will correctly sum the numbers?

A.Change to: total = total + eval(line)
B.Change to: total = total + line.strip()
C.Change to: total = total + float(line.strip())
D.Change to: total = total + int(line)
AnswerC

`line` is a string, so adding it to a float raises TypeError. Wrapping it in `float()` converts the stripped text into a numeric value, enabling correct arithmetic. `strip()` removes the trailing newline that `float()` would otherwise reject.

Why this answer

`float(line.strip())` converts the string read from the file (after removing any surrounding whitespace, including the newline character) into a float, which can then be added to the float variable `total`. The original error occurs because Python does not allow implicit addition of a string to a float.

Exam trap

Python Institute often tests the candidate's understanding that file input is always a string and must be explicitly converted to a numeric type before arithmetic, and that `strip()` alone does not change the data type.

How to eliminate wrong answers

Option A is wrong because `eval(line)` is dangerous and unnecessary; it evaluates the string as a Python expression, which could execute arbitrary code and is not a safe or recommended way to convert a string to a float. Option B is wrong because `line.strip()` returns a string, not a float, so the same TypeError would occur when trying to add a string to a float. Option D is wrong because `int(line)` would fail if the line contains a decimal point (e.g., '3.14') and would also raise a ValueError; moreover, the data is floats, not integers.

442
MCQeasy

What is the result of the following expression? d = {'a': 1} d.get('b', 0)

A.0
B.None
C.KeyError
D.1
AnswerA

dict.get returns the value for the given key, or the supplied default when the key is absent. Since 'b' is not in {'a': 1}, the method returns the default 0 rather than raising KeyError, leaving the dictionary unchanged.

Why this answer

The `get()` method on a dictionary returns the value for the given key if it exists; otherwise, it returns the default value provided as the second argument. Since key `'b'` is not in dictionary `d`, the method returns `0` (the specified default). Option A is correct because `d.get('b', 0)` explicitly supplies a default of `0`.

Exam trap

The PCEP exam often tests the distinction between `dict.get()` (which returns a default or `None`) and direct subscript access `d[key]` (which raises `KeyError`), trapping candidates who confuse the two behaviors.

How to eliminate wrong answers

Option B is wrong because `get()` returns `None` only when no default is provided and the key is missing; here a default of `0` is given. Option C is wrong because `get()` never raises a `KeyError` — that would occur with direct indexing like `d['b']`. Option D is wrong because `1` is the value for key `'a'`, not for key `'b'`.

443
MCQmedium

A quiz program stores a user's score as score = 7 and the number of questions as total = 2. The developer writes percentage = score / total * 100. What value is displayed?

A.350
B.350.0
C.3.5
D.TypeError
AnswerB

In Python 3, the / operator always performs true division, so 7 / 2 evaluates to 3.5 even though both operands are integers. Multiplying by 100 gives 350.0. The result is a float, which is why the decimal appears. This is the expected behavior for a percentage calculation.

Why this answer

Python 3 uses true division for the / operator, so dividing two integers yields a float. With score = 7 and total = 2, 7 / 2 is 3.5, and 3.5 * 100 is 350.0. The expression evaluates left to right, so the multiplication by 100 cannot be skipped.

The displayed value includes a decimal because the result type is float.

Exam trap

The trap here is expecting integer division from the / operator, as in Python 2 or many other languages, when Python 3 always returns a float.

444
MCQhard

After executing: a = 5; b = 2; c = a // b; d = a % b; e = a ** b. What is the value of (c + d) * 2 - e?

A.-20
B.-19
C.-11
D.-15
AnswerB

Integer division gives c = 2, modulo gives d = 1, and exponentiation gives e = 25. So (2 + 1) * 2 - 25 = 6 - 25 = -19, matching the computed value exactly.

Why this answer

After executing the code, a=5, b=2, c=5//2=2 (floor division), d=5%2=1 (remainder), e=5**2=25 (exponentiation). Then (c+d)*2-e = (2+1)*2-25 = 3*2-25 = 6-25 = -19. Option B is correct because it matches this calculation.

Exam trap

Python Institute often tests the distinction between floor division (//) and true division (/), and the correct order of operations (PEMDAS), where candidates may incorrectly compute c as 2.5 or misapply the exponentiation operator.

How to eliminate wrong answers

Option A is wrong because -20 would result if you mistakenly used regular division (c=2.5) and then rounded incorrectly, or if you swapped the order of operations (e.g., c+d*2-e). Option C is wrong because -11 would result if you incorrectly computed c as 5//2=2, d as 5%2=1, but then miscalculated e as 5**2=10 (confusing exponentiation with multiplication). Option D is wrong because -15 would result if you used integer division incorrectly (e.g., c=2, d=1, but then computed (c+d)*2 as 2+1*2=4, then 4-25=-21, or if you mistakenly used c=2, d=1, e=25 but then did (2+1)*2-25=6-25=-19, so -15 suggests a different arithmetic error like using c=5//2=2, d=5%2=1, e=5**2=25, but then computing (2+1)*2-25 as 2+1*2-25=2+2-25=-21, or mis-evaluating exponentiation as 5*2=10 leading to 6-10=-4, none of which match -15.

445
MCQeasy

A developer writes a program to calculate the average of three numbers: a=10; b=20; c=30; avg = a + b + c / 3; print(avg). What is the output?

A.20.0
B.10.0
C.40.0
D.60.0
AnswerC

Operator precedence evaluates division before addition, so c / 3 yields 10.0, then a + b + 10.0 gives 40.0. The float result arises because true division always returns a float in Python 3, satisfying the stem's expression exactly as written without parentheses.

Why this answer

The expression `a + b + c / 3` follows Python's operator precedence: division (`/`) has higher precedence than addition (`+`), so `c / 3` is evaluated first (30 / 3 = 10.0), then the additions are performed left to right: 10 + 20 + 10.0 = 40.0. The result is a float because division always returns a float in Python 3.

Exam trap

Python Institute often tests operator precedence by placing a division operation at the end of an expression without parentheses, tricking candidates into assuming left-to-right evaluation or that the entire sum is divided.

How to eliminate wrong answers

Option A is wrong because 20.0 would be the result if the expression were `(a + b + c) / 3` (average calculation), but the parentheses are missing. Option B is wrong because 10.0 would be the result if only `c / 3` were printed, ignoring `a` and `b`. Option D is wrong because 60.0 would be the result if the expression were `a + b + c` without division, or if the division were applied incorrectly to the entire sum without parentheses.

446
MCQhard

A Python program loads this JSON and accesses the first rule's action. Which expression gives the string "permit"?

A.data["rules"][0]["action"]
B.data["rules"][0]["action"][:5]
C.data["rules"][0]["action"][0]
D.data["rules"][1]["action"]
AnswerA

Subscripting `data["rules"]` returns the list, then `[0]` selects its first element — a dictionary — and `["action"]` retrieves that key's value, the string `"permit"`. This directly satisfies the stem's requirement to access the first rule's action field without iteration.

Why this answer

It uses the correct indexing to access the first element of the 'rules' list (index 0) and then retrieves the value associated with the key 'action' from that dictionary. This yields the string 'permit' as stored in the JSON data.

Exam trap

Python Institute often tests the distinction between accessing the first element of a list (index 0) versus the second element (index 1), and between retrieving a dictionary value by key versus slicing or indexing a string.

How to eliminate wrong answers

Option B is wrong because it attempts to slice the string 'permit' with [:5], which would return 'permit' only if the string length is exactly 5, but the correct approach is direct key access, not slicing. Option C is wrong because it uses index [0] on the string 'permit', which returns the first character 'p', not the whole string. Option D is wrong because it accesses the second rule (index 1) instead of the first rule (index 0), so it would retrieve the action of the second rule, which might not be 'permit'.

447
MCQmedium

A ticket system stores seat rows in the list rows = [[1, 2], [3, 4], [5, 6]]. A developer needs to print every individual seat number on its own line, in order, from 1 through 6. Which code accomplishes this?

A.print(rows)
B.for row in rows: print(row)
C.for seat in rows: print(seat[0])
D.for row in rows: for seat in row: print(seat)
AnswerD

The outer loop selects each inner list, and the inner loop walks that list element by element, printing 1, 2, 3, 4, 5, and 6 each on its own line. Nested loops are the standard way to traverse a list of lists, and the order is preserved because both loops advance forward through their sequences.

Why this answer

Traversing a list of lists requires nested loops: the outer loop yields each inner list, and the inner loop yields each element within it. Printing the inner element inside both loops emits every seat number in order, one per line, which matches the required output of 1 through 6.

Exam trap

The trap here is stopping at one level of iteration and printing whole inner lists instead of their individual elements.

448
Matchingmedium

Match each Python data structure to its characteristic.

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

Concepts
Matches

Ordered, immutable sequence of items

Unordered collection of unique items

Mapping of key-value pairs

Ordered, mutable sequence of items

Immutable sequence of characters

Why these pairings

Python data structures have distinct properties: lists and tuples are ordered sequences (lists mutable, tuples immutable); sets are unordered and contain unique elements; dictionaries map keys to values. Common confusions include mixing mutability/order between lists and tuples, and assuming sets maintain order.

449
MCQhard

A developer uses a tuple to store immutable configuration data: config = ('localhost', 8080, True). They then write: host, port, secure = config. What is the result of this statement?

A.host becomes 'localhost', port becomes 8080, and secure becomes True.
B.A SyntaxError occurs because the left side must be enclosed in parentheses.
C.A ValueError is raised because tuples cannot be unpacked into multiple variables.
D.host becomes the entire tuple, and port and secure are assigned None.
AnswerA

Tuple unpacking assigns the first element to host, the second to port, and the third to secure, in order. The tuple has exactly three elements, matching the three target variables. This is a concise way to extract multiple values from a tuple. The operation succeeds without error, and the variables receive the corresponding values from the tuple.

Why this answer

Tuple unpacking assigns each element of the tuple to the corresponding variable on the left side, in order. The number of variables must equal the number of elements. In this case, three variables match three elements, so host, port, and secure receive 'localhost', 8080, and True respectively.

No error occurs.

Exam trap

The trap here is assuming that tuple unpacking requires parentheses or that it fails if the tuple contains mixed types.

450
Multi-Selecteasy

Which TWO of the following are valid methods that can be called on a tuple object? (Choose two.)

Select 2 answers
A..pop()
B..index()
C..append()
D..sort()
E..count()
AnswersB, E

.index() searches a tuple for a specified value and returns the zero-based position of its first occurrence, raising ValueError when absent. Tuples support this read-only lookup because it mutates nothing, satisfying the immutability constraint while providing the membership-position query the question requires.

Why this answer

The `.index()` method is a built-in tuple method that returns the index of the first occurrence of a specified value. Tuples are immutable sequences, so they support only non-mutating methods like `.index()` and `.count()`, which do not modify the tuple.

Exam trap

The PCEP exam often tests the distinction between mutable and immutable sequence types, trapping candidates who assume that because lists have methods like `.pop()`, `.append()`, and `.sort()`, tuples must have them too, when in fact tuples only support non-mutating methods like `.index()` and `.count()`.

Page 5

Page 6 of 7

Page 7

All pages