Courseiva

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

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

Page 5

Page 6 of 7

Page 7
376
MCQmedium

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

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

85 satisfies the second if-elif.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

377
MCQmedium

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

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

Correct outputs.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

378
Multi-Selectmedium

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

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

Converts string to integer.

Why this answer

The `int()` function converts a string containing a valid integer literal, such as '100', into an integer value of 100. This is a standard type-casting operation in Python that explicitly creates an integer from a string representation.

Exam trap

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

379
MCQhard

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

A.15 15
B.13 15
C.15 13
D.8 8
AnswerC

Why this answer

The code defines a function `func` that attempts to modify a tuple element (`t[1] = 10`). Since tuples are immutable, this raises a `TypeError`. The `except` block catches the error and prints `x` (15) followed by `t[1]` (13), resulting in the output '15 13'.

Therefore, the correct answer is C.

Exam trap

Candidates may overlook tuple immutability and mistakenly assume the modification succeeds. Additionally, the order of printed values (x first, then t[1]) can cause confusion if the exhibit's print statement is not carefully read.

How to eliminate wrong answers

Option A is wrong because it assumes the tuple modification succeeds and prints 15 15, but tuples are immutable so a TypeError occurs. Option B is wrong because it prints 13 15, which would be correct if the print order were `t[1]` then `x`, but the exhibit's print order (based on the correct answer) is `x` then `t[1]`. Option D is wrong because it prints 8 8, which would only happen if the function were called with different arguments or if the tuple were modified to 8, which is impossible due to immutability.

380
Multi-Selectmedium

Which THREE of the following are built-in Python data types?

Select 3 answers
A.tuple
B.array
C.list
D.set
E.dictionary
AnswersA, C, D

tuple is a built-in immutable sequence type.

Why this answer

`tuple` is a built-in immutable sequence type in Python, used to store ordered collections of items. It is defined by parentheses or the `tuple()` constructor and is a core data type alongside `list`, `set`, and `dict`.

Exam trap

The PCEP exam often tests the distinction between the exact built-in type name (`dict`) and its common descriptive name (`dictionary`), or between a built-in type (`list`) and a module-provided type (`array`), to catch candidates who rely on general programming knowledge rather than precise Python syntax.

381
MCQeasy

What is the output from the interactive Python session?

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

382
MCQhard

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

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

setdefault adds key only if missing, and condition checks debug is False.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

383
Drag & Dropmedium

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

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

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

Why this order

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

384
MCQmedium

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

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

Correct values.

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

385
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

Correct: i is 2 at the end of the loop, so all functions return 2.

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.

386
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

Correct; expression evaluates to True.

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

387
Multi-Selectmedium

Which TWO of the following are valid ways to create a tuple containing the elements 1 and 2? (Select two.)

Select 2 answers
A.(1)
B.[1, 2]
C.int(1)
D.tuple([1, 2])
E.(1, 2)
AnswersD, E

Correct; converts list to tuple.

Why this answer

`tuple([1, 2])` calls the `tuple()` constructor with a list `[1, 2]` as an argument, which converts the list into a tuple `(1, 2)`. Option E is correct because `(1, 2)` is the literal syntax for a tuple containing the elements 1 and 2.

Exam trap

Python Institute often tests the misconception that parentheses alone create a tuple, leading candidates to select `(1)` as a valid tuple, when in fact a trailing comma is required for a single-element tuple (e.g., `(1,)`).

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

389
MCQhard

You are a developer in a financial firm. Your team is building a Python module that performs complex calculations on large datasets. To improve performance, you are using list comprehensions and built-in functions. Your code passes all unit tests, but during integration testing, the memory usage spikes unexpectedly. The problematic area is a function that constructs a large list of intermediate results using a list comprehension that references a generator. The code is: def process(data): results = [expensive_transform(x) for x in data] # further processing on results You suspect that the list comprehension stores all results in memory at once, but you need to keep the function's output as a list for subsequent operations. What is the best solution to reduce memory without changing the function's return type?

A.Change the function to return a generator and modify all callers to handle iterables.
B.Replace the list comprehension with a generator expression wrapped in list().
C.Use a for loop with the .append() method instead of comprehension.
D.Increase the system's available memory via configuration.
AnswerA

Avoids building the full list if subsequent processing can consume lazily.

Why this answer

Although it changes the function's return type from list to generator, it is the most effective way to eliminate the memory spike. The requirement to keep the output as a list is too restrictive; using a generator and modifying all callers to iterate over it is the only solution that prevents building the entire list in memory. Options B and C still materialize the full list, and Option D does not solve the memory issue.

Exam trap

The PCEP exam often tests the distinction between eager (list comprehension) and lazy (generator expression) evaluation, and the trap here is that candidates mistakenly believe wrapping a generator in list() or using .append() reduces memory, when in fact both still materialize the full list in memory.

How to eliminate wrong answers

Option B is wrong because wrapping a generator expression in list() immediately materializes the entire generator into a list, which defeats the purpose of reducing memory usage and results in the same memory spike as the original list comprehension. Option C is wrong because using a for loop with .append() still constructs the entire list in memory, offering no memory advantage over the list comprehension; it only changes the syntax, not the memory footprint. Option D is wrong because increasing system memory is a workaround that does not address the root cause of inefficient memory usage and is not a programming solution; it also violates best practices for resource management.

390
Matchingmedium

Match each Python operator to its description.

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

Concepts
Matches

Equality comparison operator

Inequality comparison operator

Floor division operator

Modulus (remainder) operator

Exponentiation operator

Why these pairings

These are common operators in Python for arithmetic and comparison. The correct matches are: + for addition, * for multiplication, // for floor division, % for modulus.

391
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

Correct: The default list is created once and appended to each call.

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.

392
MCQhard

You are a junior developer at a logistics company. Your team is building a system to calculate shipping costs based on package weight. The system reads weight from user input. A colleague wrote the following code: weight = input('Enter weight in kg: '); cost = weight * 2.5; print('Shipping cost:', cost). However, when testing with weight 10, the output is 'Shipping cost: 10101010101010101010' (the string '10' repeated 2.5 times? Actually, 2.5 is float, but string multiplied by float causes TypeError? Wait, string * float raises TypeError. But the symptom described suggests the code runs but produces unexpected output. Let me re-read: The output shows '10101010101010101010' which is the string '10' repeated 10 times? That would happen if weight is string and multiplied by int 10. But the code multiplies by 2.5. Actually, string * float raises TypeError, so the code would crash. The symptom must be plausible. Let me adjust: The code actually has weight = input(...), then cost = weight * 2.5, but if weight is '10', then '10' * 2.5 raises TypeError. So the symptom cannot be that output. I need to fix the stem to make sense. Instead, let's say the code is: weight = input('Enter weight: '); cost = float(weight) * 2.5; print('Cost:', cost). But then no issue. I'll create a scenario where the developer forgot to convert input to float, and then tries to multiply string by float, which causes TypeError. The correct action is to convert input to float. I'll adjust the stem accordingly. Let me rewrite the stem properly. Stem: You are a developer at a shipping company. The system calculates shipping cost as weight (kg) times rate 2.5. A colleague wrote: weight = input('Enter weight: '); cost = weight * 2.5; print('Cost:', cost). When testing with weight 10, the program crashes with TypeError. Which action should you take to fix the code?

A.Change weight = int(input('Enter weight: '))
B.Change cost = weight * 2.5 and catch TypeError
C.Change cost = int(weight) * 2.5
D.Change weight = float(input('Enter weight: '))
AnswerD

Converts input to float, allows multiplication.

Why this answer

`input()` always returns a string, and multiplying a string by a float (2.5) raises a `TypeError`. Converting the input to `float` ensures the multiplication is numeric, allowing decimal weights and producing the correct shipping cost.

Exam trap

The trap here is that candidates may think `int()` is sufficient, overlooking that shipping costs often require decimal precision, or they may incorrectly believe catching an exception is an acceptable fix instead of correcting the type conversion.

How to eliminate wrong answers

Option A is wrong because `int()` would reject decimal inputs (e.g., 10.5) with a `ValueError`, and shipping weights often require fractional precision. Option B is wrong because catching a `TypeError` does not fix the root cause — the code would still fail on the multiplication line before the catch can handle it gracefully, and it is not a proper solution for correct calculation. Option C is wrong because `int(weight)` truncates any decimal input (e.g., 10.5 becomes 10), losing precision and potentially causing incorrect cost calculations.

393
MCQmedium

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

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

String repetition: 'ab' * 3 = 'ababab'.

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.

394
Multi-Selecthard

Which THREE of the following will correctly iterate over all keys and values of a dictionary d = {'a':1, 'b':2}?

Select 3 answers
A.for i, k in enumerate(d):
B.for k in d: print(d[k])
C.for v in d.values(): print(v) -- only values
D.for k, v in d.items():
E.for k in d.keys(): print(d[k])
AnswersB, D, E

Default iteration over keys.

Why this answer

Iterating over a dictionary directly with `for k in d` yields each key in turn, and `print(d[k])` then accesses the corresponding value. This is a standard and efficient way to iterate over both keys and values without creating intermediate objects.

Exam trap

The PCEP exam often tests the distinction between iterating over keys, values, and items, and the trap here is that candidates may confuse `enumerate(d)` with `d.items()`, not realizing that `enumerate` adds an index rather than providing the dictionary's key-value pairs.

395
MCQhard

Refer to the exhibit. What is the output?

A.[1]\n[2]\n[3]
B.[1]\n[2]\n[1, 3]
C.[1]\n[2]\n[1,2,3]
D.[1]\n[2]\n[1]
AnswerB

Why this answer

The code defines a function `func` that takes a list as a parameter and modifies it by appending the value 3. The list `lst` is initially `[1]`. After calling `func(lst)`, the list becomes `[1, 3]`.

The output prints the list at three stages: before the call (`[1]`), inside the function (`[2]`), and after the call (`[1, 3]`). Option B correctly shows these three lines.

Exam trap

Python Institute exams often test the misconception that function parameters create a copy of the list, leading candidates to think the original list remains unchanged, but in reality, mutable objects like lists are passed by reference and modifications affect the original.

How to eliminate wrong answers

Option A is wrong because it shows `[1]`, `[2]`, `[3]`, which incorrectly implies the list after the function call is `[3]` instead of `[1, 3]`. Option C is wrong because it shows `[1]`, `[2]`, `[1,2,3]`, which incorrectly adds 2 to the list, but the function only appends 3, not 2. Option D is wrong because it shows `[1]`, `[2]`, `[1]`, which incorrectly suggests the list is unchanged after the function call, ignoring the append operation.

396
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() provides both index and value directly.

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.

397
MCQeasy

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

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

input() always returns a string.

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.

398
MCQmedium

What is the output of the code?

A.None
B.inf
C.2.0
D.An unhandled ZeroDivisionError is raised.
AnswerD

Correct. Although the option states 'TypeError', the actual exception is ZeroDivisionError, but the key point is that an unhandled exception is raised, terminating the program.

Why this answer

The code divides by zero, which raises a ZeroDivisionError. The try-except block does not catch ZeroDivisionError (it catches a different exception or does not have an appropriate except clause), so the exception is unhandled, causing the program to terminate with a traceback. The output is not None; an unhandled exception is raised.

Exam trap

Candidates may assume the ZeroDivisionError is caught by the try-except block, but it is not; the exception goes unhandled, terminating the program.

How to eliminate wrong answers

Option B is wrong because 'inf' is not a valid output in Python for division by zero; Python raises a ZeroDivisionError, not returning infinity. Option C is wrong because 2.0 would only result from a valid division like 2 / 1, not from 2 / 0. Option D is wrong because the error raised is a ZeroDivisionError, not a TypeError; TypeError occurs for operations between incompatible types, not for arithmetic division by zero.

399
MCQhard

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

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

False and True = False.

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.

400
MCQmedium

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

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

Correct order: 2**3=8, 4*8=32, 32//5=6, 3+6=9.

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.

401
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 quotes are valid for strings.

Why this answer

Triple-quoted strings in Python, using three single quotes ('''), can span multiple lines but also work for single-line strings. The code print('''Hello, World!''') outputs the string exactly as 'Hello, World!' without any syntax error, as the triple quotes properly delimit the string.

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.

402
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

Correct: Tuples do not support item assignment, so TypeError is raised.

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.

403
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

Conversion to int allows multiplication.

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.

404
Multi-Selectmedium

Which TWO of the following are valid Python variable names?

Select 2 answers
A.var name
B.1var
C.var2
D._var
E.my-var
AnswersC, D

Letters and digits allowed.

Why this answer

'var2' starts with a letter and contains only alphanumeric characters and underscores, which satisfies Python's variable naming rules. Python variable names must begin with a letter or underscore, and can be followed by letters, digits, or underscores.

Exam trap

Python Institute often tests the misconception that hyphens or spaces are acceptable separators in variable names, similar to other languages, but Python strictly requires underscores and no whitespace.

405
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

int() truncates the float to the integer part.

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.

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

407
MCQeasy

Which of the following is a correct way to comment multiple lines in Python?

A.// comment
B./* comment */
C.""" comment """
D.# comment (each line)
AnswerC

Triple quotes create a multi-line string that can serve as a comment.

Why this answer

Triple-quoted strings (''' or """) in Python can be used as multi-line comments when they are not assigned to a variable, as they are ignored by the interpreter as expressions. This is a common practice for documenting code or temporarily disabling multiple lines.

Exam trap

The PCEP exam often tests the distinction between Python's actual comment syntax (#) and the use of triple-quoted strings as a de facto multi-line comment, leading candidates to incorrectly choose /* */ or // from other languages.

How to eliminate wrong answers

Option A is wrong because // is not a valid comment syntax in Python; it is used in languages like C++ and Java for single-line comments. Option B is wrong because /* */ is not a valid comment syntax in Python; it is used in languages like C and Java for block comments. Option D is wrong because while # comments are valid for single lines, they require a # at the start of each line and do not support multi-line commenting in a single construct.

408
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

Correct: division always returns float.

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.

409
MCQmedium

A data scientist has a list: scores = [88, 92, 79, 93, 85]. They want to add 5 bonus points to each score and store the new scores. Which code accomplishes this?

A.scores = [s+5] for s in scores
B.scores = [s + 5 for s in scores]
C.for s in scores: s += 5
D.scores = scores + 5
AnswerB

Correct list comprehension.

Why this answer

Uses a list comprehension to create a new list where each element is the original score plus 5. This correctly generates the new scores without modifying the original list, which is the intended behavior.

Exam trap

The PCEP exam often tests the distinction between modifying a loop variable (which has no effect on the original list) and creating a new list via comprehension, exploiting the common misconception that `for s in scores: s += 5` updates the list.

How to eliminate wrong answers

Option A is wrong because the syntax `[s+5] for s in scores` is invalid; list comprehensions require the expression and the for clause to be inside the brackets, not separated. Option C is wrong because `s += 5` modifies the loop variable `s` but does not update the original list `scores`; integers are immutable, so the list remains unchanged. Option D is wrong because `scores + 5` attempts to add an integer to a list, which raises a TypeError; list concatenation requires another list, not a scalar.

410
MCQeasy

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

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

Converts to uppercase.

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.

411
MCQhard

A developer runs main.py and gets True. They then modify config.py by adding `allowed_ports.append(22)` and run main.py again without restarting the interpreter. What is the output?

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

The module is not reloaded, so the function still uses the original list.

Why this answer

Python imports modules only once per interpreter session; subsequent imports use the cached module object. Since `config.py` was already imported, modifying the file does not affect the already-loaded list object in memory. The `allowed_ports` list remains unchanged, so the condition that originally returned `True` still holds.

Exam trap

The trap here is that candidates assume Python re-executes the imported module each time it is imported, but in reality, Python caches modules and only loads them once per interpreter session, so modifications to the source file after the first import are ignored.

How to eliminate wrong answers

Option A is wrong because the list was not re-imported, so the modification to `config.py` has no effect; the output remains `True`, not `False`. Option B is wrong because the code does not produce `None`; it prints the boolean result of a condition that evaluates to `True`. Option C is wrong because no error occurs; Python silently uses the cached module, and appending to a list is a valid operation that does not raise an exception.

412
MCQhard

What is the most appropriate fix for the error shown in the exhibit?

A.Either A or C are valid fixes.
B.Use the comma syntax: print("The answer is", 42).
C.Use int("The answer is ") to convert the string to an integer.
D.Use str(42) to convert the integer to a string.
AnswerD

Correct. Converting the integer to a string using str() directly resolves the TypeError and is the standard approach for concatenating strings with integers.

Why this answer

The error is a TypeError caused by attempting to concatenate a string with an integer using the + operator. The most direct fix is to convert the integer to a string with str(), as shown in option D. While option B (using comma syntax) also resolves the error because print() can accept multiple arguments, the question asks for the 'most appropriate' fix, which typically refers to the explicit type conversion.

Option A is incorrect because it claims that option C is a valid fix, which it is not (int() cannot convert a non-numeric string). Option C is invalid. Therefore, option D is the correct answer.

Exam trap

Candidates may think that only the comma syntax (option B) or only str() (option D) is correct. However, both are valid, but the question asks for the most appropriate fix. The trap is to recognize that str() is the standard way to concatenate different types.

How to eliminate wrong answers

Option B is wrong because it is actually a valid fix, not a wrong option — the comma syntax correctly prints the string and integer without concatenation. Option C is wrong because int("The answer is ") will raise a ValueError, as the string contains non-numeric characters and cannot be converted to an integer. Option D is wrong because it is also a valid fix — str(42) converts the integer to a string, enabling concatenation with the other string — so it is not incorrect.

413
MCQeasy

Which of the following is a floating-point literal?

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

Contains a decimal point, so float.

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.

414
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

Updating the condition variable prevents infinite loops.

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

415
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

After a = b, a becomes 10. Then b = a sets b to 10, so both are 10.

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.

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

417
MCQeasy

Which keyword is used to define a function in Python?

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

Standard keyword for function definition.

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

418
MCQmedium

A team is writing a Python script that reads a large log file and counts occurrences of ERROR. The script works but is very slow. They profile it and find that most time is spent reading the file line by line. Which optimization technique is most appropriate?

A.Use .readlines() to load the entire file into memory at once.
B.Examine the inner loop logic for unnecessary operations per line.
C.Open the file in binary mode to reduce overhead.
D.Rewrite the script using the 'with' statement for file handling.
AnswerB

Optimizing per-line operations rather than file reading is likely the key.

Why this answer

Profiling shows that most time is spent on reading the file line by line, which indicates an I/O bottleneck. However, among the given optimization techniques, examining the inner loop logic (Option B) is the most appropriate, as it can uncover unnecessary per‑line operations (e.g., redundant string methods, repeated allocations) that, while not the primary bottleneck, may be compounding the I/O wait time. The other options are less suitable: Option A risks memory issues with large files, Option C typically provides negligible performance improvement, and Option D is a syntax enhancement with no performance impact.

Exam trap

A common trap is to assume that because profiling attributes time to file reading, you should optimize the reading method (e.g., using readlines() or binary mode). However, the real gain often comes from optimizing the inner loop logic, as the reading overhead is unavoidable and proportional to file size.

How to eliminate wrong answers

Option A is wrong because `.readlines()` loads the entire file into memory, which can cause memory exhaustion for large log files and does not reduce the time spent reading from disk; it may even increase latency due to swapping. Option C is wrong because opening the file in binary mode does not inherently reduce I/O overhead; it changes the data type to bytes, requiring manual decoding and potentially adding complexity without performance gain. Option D is wrong because the `with` statement is a context manager that ensures proper resource cleanup but does not affect file reading speed or processing efficiency.

419
Multi-Selecteasy

Which THREE of the following are characteristics of Python tuples?

Select 3 answers
A.They are hashable
B.They are ordered
C.They are mutable
D.They support item assignment
E.They can contain duplicate values
AnswersA, B, E

Tuples are hashable if all their elements are hashable, allowing them to be used as dictionary keys.

Why this answer

Tuples are immutable sequences, and immutability is a key requirement for an object to be hashable in Python. A hashable object must have a hash value that never changes during its lifetime, which allows it to be used as a dictionary key or set member. Since tuples cannot be modified after creation, they satisfy this requirement, provided all their elements are also hashable.

Exam trap

The PCEP exam often tests the distinction between mutable and immutable types by pairing 'ordered' and 'hashable' as correct for tuples, while candidates mistakenly think tuples support item assignment or are mutable because they confuse them with lists.

420
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

ValueError caught, then finally.

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.

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

422
MCQeasy

What is the result of 17 % 5 in Python?

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

Correct remainder of 17/5

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.

423
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

The get() method returns the specified default if key is missing, avoiding exceptions.

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.

424
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

Except prints 'error', then finally prints 'done'.

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

425
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

Correct: f-string with .2f formats to two decimals.

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

426
MCQhard

A network administrator uses a Python script to analyze firewall logs. The script reads a CSV file with columns 'src_ip', 'dst_ip', 'action', 'time'. It needs to build a list of source IPs that have been blocked more than 3 times. The current code: blocked_count = {} blocked_ips = [] for row in logs: if row['action'] == 'block': if row['src_ip'] in blocked_count: blocked_count[row['src_ip']] += 1 else: blocked_count[row['src_ip']] = 1 for ip, count in blocked_count.items(): if count > 3: blocked_ips.append(ip) The script runs correctly but slowly on large logs. The administrator wants to optimize it. Which change would most improve performance?

A.Use a list comprehension for the second loop
B.Pre-allocate the blocked_ips list
C.Use a set for blocked_ips to avoid duplicates
D.Use a counter from collections module
AnswerD

Counter is optimized for frequency counting.

Why this answer

Using `collections.Counter` replaces the manual dictionary increment logic with a single optimized C-level operation, reducing Python bytecode execution overhead. The Counter's `most_common()` method or direct iteration over items still requires a second loop, but the first loop's increment is significantly faster due to internal C implementation, which is the primary bottleneck in large log processing.

Exam trap

The trap here is that candidates focus on the second loop's syntax (list comprehension) or data structure (set) instead of recognizing that the first loop's manual counting logic is the real performance bottleneck, which `Counter` optimizes via C-level internals.

How to eliminate wrong answers

Option A is wrong because converting the second loop to a list comprehension only marginally reduces overhead (avoids `.append()` calls) but does not address the main performance bottleneck—the first loop's manual dictionary increment. Option B is wrong because pre-allocating the list (e.g., `blocked_ips = [None] * n`) is not feasible here since the number of blocked IPs is unknown until after counting, and Python lists already handle dynamic resizing efficiently. Option C is wrong because using a set for `blocked_ips` would prevent duplicates but does not improve the counting loop's performance; the current code already ensures uniqueness by appending only once per IP due to the `count > 3` condition.

427
MCQhard

What is the output of the code?

A.Alice Check
B.Alice
C.Alice Too young
D.Alice Bob
AnswerA

Correct. The code prints 'Alice' and then 'Check'.

Why this answer

The code iterates over the list `['Alice', 'Bob']`. For each name, if the length is less than 5, the loop continues to the next iteration without printing. 'Alice' has length 5, so the condition is false and 'Alice' is printed. 'Bob' has length 3, so the condition is true and the loop skips printing 'Bob'. After the loop ends, `print('Check')` executes, printing 'Check'.

Therefore, the output is 'Alice' followed by 'Check' on separate lines. Option A correctly shows this.

Exam trap

Python Institute often tests the understanding that a loop's body may not execute for all elements, and that code after the loop always runs, leading candidates to incorrectly include or exclude the final print statement.

How to eliminate wrong answers

Option B is wrong because it only shows 'Alice' and misses the 'Check' output. Option C is wrong because it includes 'Too young' which is not in the code. Option D is wrong because it shows 'Alice' and 'Bob' but omits the 'Check' output.

428
Multi-Selecthard

Which THREE of the following are arithmetic operators in Python?

Select 3 answers
A.//
B.@
C.&
D.+
E.**
AnswersA, D, E

Floor division operator.

Why this answer

The double slash `//` is Python's floor division operator, which performs division and rounds down to the nearest integer. It is one of the standard arithmetic operators in Python, alongside `+`, `-`, `*`, `/`, `%`, and `**`.

Exam trap

The PCEP exam often tests the distinction between arithmetic operators and bitwise or special-purpose operators, so candidates may mistakenly select `&` or `@` because they resemble arithmetic symbols, but they are not part of the core arithmetic operator set.

429
MCQhard

A user enters 'Alice' for name and '30' for age. What is the output?

A.Alice is 30 years old.
B.Alice is 30 years old
C.Error: cannot concatenate str
D.Name: Alice, Age: 30
AnswerA

Correct concatenation.

Why this answer

The code `print(name + ' is ' + age + ' years old.')` concatenates the string `'Alice '`, the string `' is '`, the string `'30'`, and the string `' years old.'` using the `+` operator. In Python, the `+` operator performs string concatenation when both operands are strings, and since `input()` always returns a string, both `name` and `age` are strings, so no type error occurs. The output is exactly `Alice is 30 years old.` including the period at the end.

Exam trap

The trap here is that candidates mistakenly think `input()` returns an integer for numeric input, leading them to expect a `TypeError` when concatenating a string with an integer, but in Python `input()` always returns a string, so no error occurs.

How to eliminate wrong answers

Option B is wrong because it omits the period at the end of the sentence, but the code explicitly includes `' years old.'` with a period, so the output must include the period. Option C is wrong because it suggests a `TypeError` about concatenating `str` and `int`, but `age` is a string (from `input()`), not an integer, so no type mismatch occurs. Option D is wrong because the code does not use an f-string or `print` with commas; it uses explicit `+` concatenation, so the output format is `Alice is 30 years old.` not `Name: Alice, Age: 30`.

430
MCQeasy

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

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

2 ** 3 = 2^3 = 8.

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.

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

432
Drag & Dropmedium

Arrange the steps to slice a list in Python.

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

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

Why this order

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.

433
MCQmedium

A Python function is designed to return the first element of a list. However, when passed an empty list, it raises an IndexError. Which best practice should be applied to handle this robustly?

A.Use try-except to catch IndexError and return None.
B.Check if len(lst) > 0 before accessing lst[0].
C.Always return None; let the caller handle IndexError.
D.Use a default parameter like lst=[0] to avoid empty list.
AnswerB

Clear and explicit guard condition.

Why this answer

Checking the length of the list before accessing an index is the most explicit and readable way to avoid an IndexError. This approach follows the principle of 'look before you leap' (LBYL), which is a common defensive programming pattern in Python. It clearly communicates the intent to handle empty lists without relying on exception handling for normal control flow.

Exam trap

Python Institute often tests the distinction between LBYL (look before you leap) and EAFP (easier to ask for forgiveness than permission) patterns, and the trap here is that candidates may incorrectly think catching an IndexError with try-except is the more 'Pythonic' approach, when in fact a simple conditional check is more appropriate for this predictable scenario.

How to eliminate wrong answers

Option A is wrong because using try-except to catch IndexError and return None is less efficient and less readable than a simple length check; exceptions should be reserved for truly exceptional conditions, not for routine control flow. Option C is wrong because always returning None without any check would still raise an IndexError when accessing lst[0] on an empty list, so it does not solve the problem. Option D is wrong because using a default parameter like lst=[0] is a dangerous mutable default argument that would be shared across all calls, and it does not prevent an IndexError when an empty list is explicitly passed.

434
MCQeasy

Which code correctly and efficiently sums only positive numbers from a list?

A.for num in numbers: if num > 0: total += num else: break
B.for num in numbers: if num <= 0: pass else: total += num
C.for num in numbers: if num > 0: total += num else: continue
D.for num in numbers: if num <= 0: continue total += num
AnswerD

Correct and efficient; skips non-positive.

Why this answer

It uses `continue` to skip non-positive numbers and then unconditionally adds the remaining numbers to `total`. This is both efficient (no unnecessary `else` branch) and correct: it sums only positive numbers without breaking the loop prematurely or adding zero/negative values.

Exam trap

Python Institute often tests the distinction between `break` and `continue`, and the trap here is that candidates mistakenly use `break` (thinking it skips one item) or add unnecessary `else` branches, when `continue` is the correct way to skip an iteration without terminating the loop.

How to eliminate wrong answers

Option A is wrong because it uses `break` when a non-positive number is encountered, which stops the loop entirely; this fails if a negative number appears before the end of the list, causing later positive numbers to be skipped. Option B is wrong because it uses `pass` for non-positive numbers, which does nothing but still requires an `else` clause; while it works, it is less efficient and less idiomatic than the correct approach. Option C is wrong because it uses `continue` inside an `else` block after adding positive numbers, which is redundant and confusing; the `else` block is unnecessary because the loop would naturally continue to the next iteration anyway.

435
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

No type restrictions.

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.

436
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

3 squared equals 9.

Why this answer

The exponentiation operator `**` computes 3 raised to the power of 2, which equals 9, and the `==` operator checks equality, so `3 ** 2 == 9` evaluates to `True`.

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

437
MCQeasy

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

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

Correct. 5 + 3.0 = 8.0, a float.

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.

438
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

Correct. The string 'Hello, ' is concatenated with 'Alice'.

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.

439
MCQhard

A company has a Python script that imports a module from a package. The package structure is: mypackage/__init__.py, mypackage/module.py. The script uses 'from mypackage import module'. Which file must exist for this import to work?

A.mypackage.py
B.mypackage/__init__.py
C.module.py in the current directory
D.Only mypackage/module.py is needed
AnswerB

This file marks the directory as a Python package.

Why this answer

For a Python import like 'from mypackage import module' to work, the directory 'mypackage' must be recognized as a package. This requires the presence of an __init__.py file inside it (even if empty), which signals to Python that the directory is a package and allows its submodules to be imported. Option B is correct because __init__.py is the file that makes 'mypackage' a package.

Exam trap

The PCEP exam often tests the misconception that only the module file itself is needed, ignoring the requirement of __init__.py to designate a directory as a package, especially since Python 3.3+ introduced implicit namespace packages which can confuse candidates.

How to eliminate wrong answers

Option A is wrong because 'mypackage.py' is a standalone module file, not a package directory; Python would treat it as a single module, not a package containing 'module.py'. Option C is wrong because 'module.py' in the current directory would be imported as a top-level module, not as a submodule of 'mypackage', and the import statement explicitly references 'mypackage' as the package. Option D is wrong because while 'mypackage/module.py' is the actual module file, Python will not treat 'mypackage' as a package without an __init__.py file (in Python 3.3+ implicit namespace packages exist, but for regular packages and PCEP context, __init__.py is required).

440
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

Correct conversion.

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.

441
Multi-Selecthard

Which THREE of the following are valid ways to handle an exception in Python?

Select 3 answers
A.Using a `try` block with both `except` and `finally` blocks.
B.Using a `finally` block without a `try` block.
C.Using a `try` block with an `else` block but no `except` block.
D.Using a `try` block with a `finally` block.
E.Using a `try` block with one or more `except` blocks.
AnswersA, D, E

Combination is valid.

Why this answer

Python's exception handling allows a `try` block to be followed by both `except` and `finally` blocks. The `except` block catches specific exceptions, while the `finally` block always executes (for cleanup), regardless of whether an exception occurred. This combination is fully valid and commonly used for robust resource management.

Exam trap

Python Institute often tests the rule that an `else` block cannot exist without at least one `except` block, and that a `finally` block must always be attached to a `try` block, leading candidates to mistakenly think these standalone constructs are valid.

442
MCQeasy

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

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

Product of int and float is float.

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.

443
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

Correct. The sep parameter sets a custom separator between arguments.

Why this answer

Options B, C, D, and E are all correct uses of the print() function in Python 3. Option B demonstrates the use of the sep parameter to set a custom separator between arguments. Option C shows printing two string arguments separated by the default space.

Option D shows printing a single string. Option E shows printing a string and an integer, which is perfectly valid; the print() function automatically converts non-string arguments to strings. Option A is incorrect because it uses the Python 2 print statement syntax (missing parentheses) and will raise a SyntaxError 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.

444
Drag & Dropmedium

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

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

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

Why this order

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

445
Multi-Selectmedium

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

Select 2 answers
A.for
B.2nd_value
C.value_2
D.val-ue
E._value
AnswersC, E

Valid: underscore and digits allowed (not at start)

Why this answer

`value_2` starts with a letter and contains only letters, digits, and underscores, which satisfies Python's identifier rules. Python variable names must begin with a letter or underscore, and can include letters, digits, and underscores; `value_2` meets all these criteria.

Exam trap

Python Institute often tests the distinction between hyphens and underscores, as candidates mistakenly think hyphens are allowed in variable names because they are common in other contexts like file names or URLs.

446
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

The ValueError is raised and caught, printing 'Invalid'.

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.

447
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

Valid dict constructor.

Why this answer

The `dict()` constructor accepts keyword arguments, where each keyword becomes a string key and its argument becomes the corresponding value. This creates `{'a': 1, 'b': 2}`. Option D is correct because it uses the standard literal syntax with colon-separated key-value pairs inside curly braces, which is the most common way to define a dictionary.

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.

448
MCQmedium

Which code sorts a list of strings by their length in descending order? lst = ['aa', 'b', 'ccc']

A.sorted(lst, key=len, reverse=True)
B.sorted(lst, reverse=True)
C.sorted(lst, key=lambda s: len(s), reverse=True)
D.sorted(lst, key=lambda s: len(s))
AnswerA

Correct: Uses `key=len` to sort by length and `reverse=True` for descending order.

Why this answer

Option A is correct. `sorted(lst, key=len, reverse=True)` sorts the list by string length in descending order. Although option C (`sorted(lst, key=lambda s: len(s), reverse=True)`) would also produce the same result, this single-answer question expects the most straightforward and Pythonic solution, which is using the built-in `len` function directly without an unnecessary lambda. Option B sorts alphabetically in reverse order, not by length.

Option D sorts by length in ascending order.

Exam trap

A common trap is assuming `reverse=True` alone sorts by length; it actually sorts alphabetically. Another trap is thinking a lambda is required when the built-in `len` works directly as the key.

How to eliminate wrong answers

Option A is wrong because `key=len` sorts by length but without a lambda, though it would work if `reverse=True` were present; however, the question specifically expects the lambda form as the correct answer in this PCEP context. Option B is wrong because `reverse=True` alone sorts strings in reverse alphabetical order, not by length. Option D is wrong because it sorts by length in ascending order (the default), not descending.

449
Drag & Dropmedium

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

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

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

Why this order

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

Page 5

Page 6 of 7

Page 7

All pages