Courseiva

Certified Entry-Level Python Programmer PCEP (PCEP) — Questions 451–482

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

Page 6

Page 7 of 7

451
MCQmedium

What is the data type of the expression (3.14 > 2) and ('a' < 'b')?

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

Both comparisons yield Boolean values, and the `and` operator returns a `bool` when combining them. This satisfies the stem's requirement for the expression's data type: `3.14 > 2` evaluates to `True`, `'a' < 'b'` evaluates to `True`, and `True and True` produces the Boolean result `True`.

Why this answer

The expression (3.14 > 2) evaluates to True because 3.14 is greater than 2, and ('a' < 'b') evaluates to True because in Python string comparison uses lexicographic order based on Unicode code points ('a' has code point 97, 'b' has 98). The 'and' operator combines these two Boolean values, resulting in True, which is of type bool. Therefore, the entire expression's data type is bool.

Exam trap

Python Institute often tests the misconception that the 'and' operator returns a Boolean only when both operands are Boolean, but in Python it can return any operand type; however, in this specific case both operands are comparisons that yield bool, so the result is bool, and candidates may incorrectly think the result is int because True/False are subclasses of int.

How to eliminate wrong answers

Option B (float) is wrong because the expression does not produce a floating-point number; it produces a Boolean result from comparison and logical operators. Option C (str) is wrong because the expression involves comparisons and a logical operator, not string concatenation or manipulation, so the result is not a string. Option D (int) is wrong because while Booleans in Python are a subclass of int (True equals 1, False equals 0), the expression's type is explicitly bool, not int, and the question asks for the data type of the expression, which is bool.

452
MCQhard

What is the output of: print(2 ** 3 ** 2)?

A.512
B.12
C.64
D.256
AnswerA

The exponentiation operator ** is right-associative, so 3 ** 2 evaluates first to 9, then 2 ** 9 yields 512. Left-to-right evaluation would give 64, but Python's grammar groups the rightmost operation first, producing 512.

Why this answer

In Python, the exponentiation operator ** is right-associative, meaning that `2 ** 3 ** 2` is evaluated as `2 ** (3 ** 2)`, not `(2 ** 3) ** 2`. First, `3 ** 2` equals 9, then `2 ** 9` equals 512. Thus, the correct output is 512.

Exam trap

The trap here is that candidates often assume left-to-right associativity for all operators, forgetting that ** is right-associative, leading them to pick 64 instead of 512.

How to eliminate wrong answers

Option B (12) is wrong because it incorrectly assumes addition or multiplication-like behavior, not exponentiation. Option C (64) is wrong because it results from left-associative evaluation `(2 ** 3) ** 2` = 8 ** 2 = 64, which is not how Python handles chained exponentiation. Option D (256) is wrong because it might come from miscomputing `2 ** 8` or confusing exponentiation with bitwise shifts.

453
MCQhard

A Python developer is writing a script that processes a list of temperatures in a loop. Inside the loop, a conditional block handles sub-zero readings by appending a warning to a report. The developer notices that the loop body is executing even for temperatures that are not sub-zero. Which statement about Python's `if`/`elif`/`else` structure explains why a block guarded by `if temp < 0:` should not execute for a temperature of 5?

A.The `if` block executes whenever the loop variable is reassigned, regardless of the condition's truth value.
B.The `if` block executes only if a previous `elif` condition was also False, making it dependent on sibling clauses.
C.The `if` block executes for every iteration because Python evaluates conditions after running the block once.
D.The `if` block executes only when its condition evaluates to a truthy value; since `5 < 0` is False, the block is skipped.
AnswerD

Python evaluates the condition `temp < 0` and, for a temperature of 5, produces the boolean False. A false condition causes the indented block under `if` to be skipped entirely, and control passes to any `elif` or `else` clause or to the next statement after the structure. This is the fundamental rule governing conditional execution.

Why this answer

Conditional blocks in Python execute based on the truth value of their condition, evaluated before the block runs. Because `5 < 0` is False, the guarded block is skipped and control moves on. The other statements misdescribe evaluation order, trigger conditions, or dependencies among sibling clauses, none of which match Python's top-down conditional evaluation model.

Exam trap

The trap here is assuming an `if` block can be triggered by side effects like variable reassignment or sibling clauses, when only the truth value of its own condition controls execution.

454
MCQmedium

A junior developer writes: print('Hello' + 5). This code raises an error. What is the best way to fix it?

A.print('Hello' * 5)
B.print('Hello' + str(5))
C.print('Hello', 5)
D.print('Hello' + '5')
AnswerB

Explicitly converting the integer with str() resolves the TypeError, because Python's + operator requires both operands to be the same sequence type for concatenation. It satisfies the stem's constraint of fixing the error while preserving the original concatenation intent, yielding 'Hello5' rather than altering the output format.

Why this answer

Python's `+` operator for strings requires both operands to be strings. The code `print('Hello' + 5)` raises a `TypeError` because it attempts to concatenate a string with an integer. Using `str(5)` converts the integer to the string `'5'`, allowing the concatenation to succeed and print `Hello5`.

Exam trap

Python Institute often tests the distinction between concatenation (`+`) and multiple arguments in `print()`, where candidates may think `print('Hello', 5)` produces `Hello5` instead of `Hello 5` due to the default `sep=' '` parameter.

How to eliminate wrong answers

Option A is wrong because `'Hello' * 5` does not concatenate; it repeats the string 5 times, producing `HelloHelloHelloHelloHello`, which changes the intended output. Option C is wrong because `print('Hello', 5)` passes two separate arguments to `print()`, which prints them with a space separator (e.g., `Hello 5`), not as a single concatenated string. Option D is wrong because `'Hello' + '5'` works syntactically but does not fix the original error; it simply uses a string literal `'5'` instead of converting the integer `5`, which would still fail if the variable were truly an integer (e.g., from user input).

455
MCQeasy

Refer to the exhibit. What is the output?

A.3.0 1.0
B.3 3
C.3.333 1
D.3 1
AnswerD

The exhibit's code produces two values on one line separated by a space, matching the stem's expected output. The first value derives from the initial computation and the second from the subsequent operation, giving the precise sequence 3 1 as shown.

Why this answer

The code in the exhibit is `print(10//3, 10%3)`. The `//` operator performs floor division, which for positive numbers truncates the decimal part, so `10//3` yields 3. The `%` operator returns the remainder of the division, `10%3` yields 1.

Thus the output is '3 1'.

Exam trap

Python Institute often tests the difference between `/` (true division) and `//` (floor division) and `%` (modulo), and the trap here is that candidates confuse the modulo operator `%` with floor division `//`, expecting the integer quotient instead of the remainder.

How to eliminate wrong answers

Option A is wrong because `3.0 1.0` would result from `print(10/3, 10%3)` only if both results were explicitly cast to float, but `10%3` returns an integer `1`, not `1.0`. Option B is wrong because `3 3` would imply both operators returned integers, but `10/3` returns a float, not an integer. Option C is wrong because `3.333 1` would be the output of `print(10/3, 10%3)` only if the first value were truncated to three decimal places, but Python's default float representation does not round to three decimal places; it prints the full precision.

456
MCQhard

A developer writes a function `def process(data):` that uses a try-except-else-finally block. The try block reads from a file, the except block handles IOError, the else block processes the data, and the finally block closes the file. If no exception occurs, which blocks execute and in what order?

A.try, except, finally
B.try, else, except, finally
C.try, else, finally
D.try, finally
AnswerC

When no exception occurs in the try block, the else block executes after the try block completes successfully. The finally block always executes, regardless of exceptions, so it runs last. The except block is skipped because no exception was raised. Thus the order is try, else, finally.

Why this answer

In a try-except-else-finally structure, the try block runs first. If it completes without raising an exception, the else block executes. The finally block always executes, regardless of whether an exception occurred.

The except block only runs if an exception is raised. Therefore, with no exception, the order is try, else, finally.

Exam trap

The trap here is assuming that the else block runs only if an exception occurs, or that the except block always runs, but the else block is specifically for the no-exception path.

457
MCQmedium

What is the output of the code in the exhibit?

A.3
B.4
C.3.0
D.3.3333333333333335
AnswerA

The loop iterates over the list `[1, 2, 3]`, and the accumulator variable is reassigned on each pass rather than appended to, so only the final element survives. Printing after the loop therefore yields the last value, 3, satisfying the stem's requirement to trace the code's actual output.

Why this answer

The code performs integer division using the // operator, which in Python returns the floor of the division result for positive numbers. Since 10 // 3 equals 3 (the integer part of 10/3), the output is 3. Option A is correct because integer division discards the fractional part.

Exam trap

Python Institute often tests the distinction between / (true division returning a float) and // (floor division returning an int), tricking candidates who confuse the two operators or forget that integer division discards the remainder.

How to eliminate wrong answers

Option B is wrong because it assumes the result is 4, which would only occur if the code used ceiling division or an incorrect operation. Option C is wrong because it outputs 3.0, which would result from true division (/) rather than integer division (//). Option D is wrong because it outputs the full floating-point result of 10/3 (3.3333333333333335), which is produced by the / operator, not the // operator.

458
MCQmedium

A system administrator is writing a Python script to monitor server uptime. The script reads a log file line by line, parses timestamps, and stores them in a list. It then loops through the list to detect gaps longer than 5 minutes that indicate a crash. However, the script keeps missing crashes. The current loop is a for loop that iterates over the list using indices. The administrator suspects the loop logic. The loop uses 'for i in range(len(timestamps)-1): if timestamps[i+1] - timestamps[i] > 300: print("Crash detected")'. Timestamps are integers representing seconds since epoch. What is the most likely cause of missed crashes and the best fix?

A.The loop should use range(len(timestamps)) instead of -1
B.The difference should be computed as timestamps[i] - timestamps[i+1]
C.The comparison should be > 300, but use > 300.0
D.The timestamps list may not be sorted
AnswerD

Unsorted timestamps break the adjacent-pair comparison: the loop only checks consecutive list entries, so a genuine gap can sit between values that are not neighbours in time. Sorting the list before looping restores chronological adjacency, ensuring every real interval exceeding 300 seconds is detected.

Why this answer

The loop assumes timestamps are in chronological order, but if the list is unsorted, adjacent elements may not represent consecutive events, causing the time difference to be negative or misleading, and thus missing actual gaps. Sorting the list before the loop ensures that timestamps[i+1] - timestamps[i] correctly reflects the time between consecutive log entries.

Exam trap

Python Institute often tests the assumption that data structures are in the expected order, and the trap here is that candidates focus on off-by-one errors or type issues while overlooking the fundamental requirement that the list must be sorted for pairwise difference logic to work.

How to eliminate wrong answers

Option A is wrong because using range(len(timestamps)) would cause an IndexError on the last iteration when accessing timestamps[i+1]. Option B is wrong because subtracting timestamps[i] from timestamps[i+1] (assuming sorted order) gives a positive difference for increasing timestamps, which is correct; reversing the order would yield negative values that never exceed 300. Option C is wrong because comparing integers with > 300 is functionally identical to > 300.0 in Python; the type mismatch does not affect comparison logic.

459
MCQeasy

An inventory script stores product quantities in a list named stock. The script must print the running total of quantities from the start of the list up to, but not including, the first zero quantity it encounters. Which code fragment produces this behavior?

A.total = 0 for q in stock: total += q if q == 0: break print(total)
B.total = 0 for q in stock: if q == 0: break total += q print(total)
C.total = 0 for q in stock: if q == 0: continue total += q print(total)
D.total = 0 for q in stock: total += q if q == 0: continue print(total)
AnswerB

This loop adds each quantity to total and immediately exits with break when a zero is found, so only elements before the first zero are summed. Because the test occurs before the addition, the zero itself is never added, matching the requirement exactly.

Why this answer

The requirement is to accumulate quantities until the first zero appears, then stop without adding that zero. Placing the zero test before the addition and exiting with break achieves exactly this, because the loop terminates before the zero can be added to the running total.

Exam trap

The trap here is assuming that break and continue behave the same way inside a loop when they actually exit versus skip.

460
MCQmedium

Given the tuple t = (1, 2, 3, 4, 5), which expression returns the last element?

A.t[-1]
B.t[5]
C.t[4]
D.t[0]
AnswerA

Negative indexing counts from the end, so t[-1] returns the final element, 5. This directly satisfies the stem's requirement for the last element, whereas t[0] gives the first and t[5] raises an IndexError because indices stop at 4.

Why this answer

In Python, negative indices count from the end of a sequence. For the tuple t = (1, 2, 3, 4, 5), t[-1] accesses the last element (5), because -1 refers to the final position. This is a standard feature of Python's sequence indexing.

Exam trap

A common trap in PCEP exams is that candidates may use a hardcoded index like t[4] which works for this specific tuple but fails if the tuple length changes. The correct dynamic way is t[-1], which always references the last element regardless of tuple length.

How to eliminate wrong answers

Option B is wrong because t[5] attempts to access index 5, which is out of range for a tuple with indices 0 through 4, raising an IndexError. Option C is wrong because t[4] returns the element at index 4, which is 5, but this is the last element only coincidentally; the question asks for an expression that returns the last element in general, and t[4] is not a robust way to do it if the tuple length changes. Option D is wrong because t[0] returns the first element (1), not the last.

461
MCQhard

What is the scope of a variable defined inside a function?

A.Global
B.Built-in
C.Local
D.Nonlocal
AnswerC

Variables created inside a function exist only within that function's local namespace, which Python binds at call time and discards on return. This satisfies the stem's scope constraint: the name is unreachable from module level or any other function, so it cannot leak or collide with globals of the same name.

Why this answer

In Python, any variable assigned inside a function (without global or nonlocal declarations) has local scope. This means it is only accessible within that function's block and is destroyed when the function returns, as per Python's LEGB (Local, Enclosing, Global, Built-in) rule.

Exam trap

The PCEP exam often tests the misconception that any variable inside a function is automatically global or that 'nonlocal' applies to simple (non-nested) functions, leading candidates to pick 'Global' or 'Nonlocal' instead of 'Local'.

How to eliminate wrong answers

Option A is wrong because a variable defined inside a function is not automatically global; it would need an explicit 'global' declaration to be treated as global. Option B is wrong because built-in scope refers to names like 'print' or 'len' that are pre-defined in Python's builtins module, not to user-defined variables inside a function. Option D is wrong because 'nonlocal' applies to variables in nested (enclosing) function scopes, not to a variable defined directly inside a single function.

462
MCQmedium

A developer is reviewing a script that processes user data. The script contains the following lines: name = "Alice" age = 30 print(name + " is " + age) When executed, the script raises a TypeError. Which of the following changes will make the script run without error and produce the output "Alice is 30"?

A.Change the print statement to: print(name + " is " + str(age))
B.Change the print statement to: print(name + " is " + age + " years")
C.Change the print statement to: print(name + " is " + int(age))
D.Change the print statement to: print(name + " is " + float(age))
AnswerA

The TypeError occurs because the + operator cannot concatenate a string and an integer. Wrapping age with str() converts the integer to its string representation, allowing concatenation. This is the standard way to combine text and numbers in Python when not using f-strings or the format() method. The output will be exactly "Alice is 30".

Why this answer

The TypeError arises from attempting to concatenate a string and an integer using the + operator. Python requires both operands to be strings for concatenation. Converting the integer to a string with str() allows the concatenation to succeed.

The other options either leave the type mismatch or convert to other numeric types, which still cannot be concatenated with a string.

Exam trap

The trap here is assuming that Python automatically converts numbers to strings during concatenation, but the + operator is strict about operand types.

463
Multi-Selecteasy

Which TWO of the following exceptions are built-in Python exceptions? (Select exactly 2)

Select 2 answers
A.ZeroDivisionError
B.KeyError
C.StringError
D.NumberError
E.ListError
AnswersA, B

Built-in exception for division by zero.

Why this answer

ZeroDivisionError is a built-in Python exception that is raised when the second operand of a division or modulo operation is zero. It is part of Python's standard exception hierarchy and is commonly encountered in arithmetic operations.

Exam trap

Python Institute often tests the distinction between built-in exceptions and non-existent exceptions like StringError, NumberError, or ListError, which are not part of Python's standard library, to catch candidates who guess based on naming patterns rather than actual Python knowledge.

464
MCQmedium

What is the output when the following code is executed? try: print(1/0) except ZeroDivisionError: print("Cannot divide by zero")

A.Cannot divide by zero
B.The program crashes with an unhandled exception
C.Result: 0
D.Unsupported operand
AnswerA

Dividing 1 by 0 raises a ZeroDivisionError, which the except clause catches by matching that exact exception type. The handler then executes its print statement, emitting the string "Cannot divide by zero" instead of terminating with a traceback. This satisfies the stem's requirement to show the caught-exception output.

Why this answer

The code inside the try block attempts to divide by zero, which raises a ZeroDivisionError. The except block catches this exception and executes its print statement, outputting 'Cannot divide by zero'.

Exam trap

Python Institute often tests the distinction between an unhandled exception (crash) and a caught exception (graceful handling). In this case, the exception is caught, so the program does not crash.

How to eliminate wrong answers

Option B is wrong because the program does not crash with an unhandled exception; the ZeroDivisionError is caught by the try-except block, so execution continues gracefully. Option C is wrong because division by zero does not yield 0; Python raises an exception instead of returning a numeric result. Option D is wrong because 'Unsupported operand' is not a Python error message; the actual error is ZeroDivisionError, which occurs when the divisor is zero, not due to operand type mismatch.

465
MCQmedium

A developer needs to implement a loop that prints numbers from 10 down to 1. Which loop correctly achieves this?

A.for i in range(10, 0, -1): print(i)
B.for i in range(10, 0): print(i)
C.for i in reversed(range(1, 10)): print(i)
D.for i in range(10, 1, -1): print(i)
AnswerA

range(10, 0, -1) starts at 10, stops before 0, and steps by -1, yielding 10 down to 1. The stop value is exclusive, so 0 is correctly omitted, matching the descending sequence the developer requires.

Why this answer

`range(10, 0, -1)` generates numbers from 10 down to 1 inclusive. The start is 10, the stop is 0 (exclusive), and the step is -1, so the sequence is 10, 9, 8, ..., 1. This matches the requirement exactly.

Exam trap

Python Institute often tests the exclusive nature of the stop argument in `range()`, leading candidates to forget that the stop value is never included in the sequence.

How to eliminate wrong answers

Option B is wrong because `range(10, 0)` defaults to a step of 1, and since start > stop with a positive step, it produces an empty sequence — nothing is printed. Option C is wrong because `reversed(range(1, 10))` yields numbers from 9 down to 1, missing 10 entirely. Option D is wrong because `range(10, 1, -1)` stops at 2 (since stop is exclusive), so it prints 10 down to 2, missing 1.

466
MCQhard

A developer wants to create a tuple that contains a single element, the integer 5. Which of the following expressions produces exactly that?

A.t = (5)
B.t = (5, 5)
C.t = tuple(5)
D.t = (5,)
AnswerD

The trailing comma after 5 is crucial; it tells Python that this is a tuple with one element. Without the comma, (5) would be an int. This is the standard way to create a single-element tuple.

Why this answer

A single-element tuple requires a trailing comma to distinguish it from a parenthesized expression. The expression (5,) creates a tuple containing the integer 5, while (5) is just the integer. The tuple() constructor can also be used with an iterable, but not with a single integer.

The two-element tuple is incorrect because it contains two items.

Exam trap

The trap here is forgetting the trailing comma in a single-element tuple, leading to the creation of an integer instead of a tuple.

467
MCQeasy

Which loop is more efficient for iterating over a large list when you only need the values, not indices?

A.for i in range(len(mylist)): value = mylist[i]
B.for i, value in enumerate(mylist):
C.for value in mylist:
D.for value in mylist[::-1]:
AnswerC

Iterating directly with `for value in mylist` avoids index lookups and the overhead of `range()` and `len()` calls, yielding each element straight from the list's iterator. This satisfies the stem's efficiency constraint for large lists where indices are unnecessary, giving cleaner, faster traversal than index-based loops.

Why this answer

Iterating directly over the list with `for value in mylist:` avoids the overhead of indexing or enumeration. This is the most efficient approach in Python for accessing only the values, as it uses the list's internal iterator, which is implemented in C and involves no function calls or index lookups per iteration.

Exam trap

Python Institute often tests the misconception that `enumerate()` is always the best choice for iteration, but the trap here is that candidates overlook the specific requirement ('only the values, not indices') and choose a more general but less efficient option like B or A.

How to eliminate wrong answers

Option A is wrong because it uses `range(len(mylist))` and then accesses each element via indexing (`mylist[i]`), which adds the overhead of calling `range()` and performing a list lookup each iteration, making it less efficient. Option B is wrong because `enumerate()` yields both index and value, which is unnecessary when only values are needed, adding the overhead of tuple unpacking and an extra counter. Option D is wrong because `mylist[::-1]` creates a reversed copy of the entire list in memory, which is both time- and space-inefficient for large lists, and then iterates over that copy.

468
Multi-Selecthard

A developer is writing a Python script to process a list of integers representing inventory counts. The developer needs to iterate over the list and, for each element, perform an action, but also needs to be able to terminate the entire loop early when a sentinel value (0) is encountered. Which two statements about loop control in Python are correct? (Choose two.)

Select 2 answers
A.The continue statement terminates the loop and resumes execution after the loop.
B.The continue statement skips the rest of the current iteration and proceeds to the next iteration of the loop.
C.The break statement immediately exits the innermost enclosing loop.
D.A for loop in Python automatically stops when it encounters a None value in the sequence.
E.The break statement can be used outside a loop to exit a function early.
AnswersB, C

The continue statement abandons the remaining statements in the current loop body and jumps to the next iteration. It does not terminate the loop. In the inventory scenario, continue could be used to skip processing for a particular value while still examining subsequent elements, which is different from early termination.

Why this answer

The break statement exits the innermost loop immediately, which is suitable for stopping on a sentinel value. The continue statement skips to the next iteration without terminating the loop. These two control statements are fundamental for managing loop execution and are distinct from return, which exits a function.

Exam trap

The trap here is confusing break with return or assuming that continue terminates the loop, when it only skips the current iteration.

469
Drag & Dropmedium

Arrange the steps to handle an exception in Python using try-except.

Drag or tap steps into the slots.

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

Why this order

Exception handling wraps risky code in try, catches exceptions with except, and optionally includes else and finally.

470
MCQmedium

A quality engineer tracks defect counts per shift in a list called defects. She needs the running total of all defects after every shift, producing a list of cumulative sums with the same length as defects. Which approach produces that cumulative list?

A.cumulative = [] for d in defects: cumulative.append(sum(defects))
B.total = 0 cumulative = [] for d in defects: cumulative.append(total) total += d
C.cumulative = [defects[i] + defects[i+1] for i in range(len(defects))]
D.total = 0 cumulative = [] for d in defects: total += d cumulative.append(total)
AnswerD

The accumulator total starts at zero, and each iteration adds the current defect count before appending the updated total to the new list. Because the append happens after the addition, the resulting list holds the cumulative sum at each shift and has exactly the same length as the defects list, which is what the engineer needs.

Why this answer

A running total requires an accumulator initialized before the loop, updated with each element, and recorded after the update. Appending after adding yields a cumulative value for every shift and keeps the output length equal to the input length. Appending before adding shifts all values by one position, and recomputing the whole-list sum each iteration produces a repeated grand total instead.

Exam trap

The trap here is placing the append before the addition, which yields a list that is shifted by one and never reaches the final total.

471
MCQmedium

A developer is writing a Python script to compare two numbers. They write the following code: x = 10 y = 20 result = x > y or x < y and y > 15 print(result) What is printed?

A.True
B.The output is 10 > 20 or 10 < 20 and 20 > 15, which is not a boolean value.
C.False
D.An error occurs because you cannot mix 'or' and 'and' without parentheses.
AnswerA

The expression is evaluated according to operator precedence: comparison operators have higher precedence than logical operators, and 'and' has higher precedence than 'or'. First, x > y is False, x < y is True, and y > 15 is True. Then, x < y and y > 15 evaluates to True and True, which is True. Finally, False or True evaluates to True. So the output is True.

Why this answer

Logical operators in Python follow a specific precedence: 'and' is evaluated before 'or'. Also, comparison operators are evaluated before logical operators. Thus, the expression is grouped as (x > y) or ((x < y) and (y > 15)).

Substituting values: (False) or (True and True) = False or True = True. Therefore, the output is True.

Exam trap

The trap here is assuming that logical operators are evaluated left-to-right without considering that 'and' has higher precedence than 'or'.

472
MCQeasy

A dictionary student = {'name': 'John', 'age': 20}. To safely get the grade with a default of 'N/A', which code should be used?

A.student.get('grade', 'N/A')
B.student['grade']
C.student.fetch('grade', 'N/A')
D.student['grade'] or 'N/A'
AnswerA

The get method returns the value for the given key, or the supplied default when the key is absent. Using student.get('grade', 'N/A') avoids a KeyError because 'grade' is not present, satisfying the requirement for safe retrieval with a fallback.

Why this answer

The `get()` method of a dictionary safely retrieves the value for a given key, returning a default value (here `'N/A'`) if the key does not exist. This avoids raising a `KeyError` when the key `'grade'` is missing from the dictionary.

Exam trap

Python Institute often tests the distinction between safe dictionary access methods (`get()`) and direct indexing (`[]`), trapping candidates who think the `or` operator can short-circuit a `KeyError` or who invent non-existent methods like `fetch()`.

How to eliminate wrong answers

Option B is wrong because using `student['grade']` directly raises a `KeyError` if the key `'grade'` does not exist, which is not safe. Option C is wrong because dictionaries have no `fetch()` method; this is not a valid Python dictionary operation. Option D is wrong because `student['grade'] or 'N/A'` still evaluates `student['grade']` first, which raises a `KeyError` if the key is missing, and the `or` expression never executes.

473
MCQhard

A developer writes the following code: values = [10, 20, 30, 40, 50] result = values[1:4] What does the variable result contain after execution?

A.[20, 30, 40]
B.[20, 30, 40, 50]
C.[10, 20, 30]
D.[10, 20, 30, 40]
AnswerA

Slicing uses a start index that is included and a stop index that is excluded. Starting at index one includes twenty, and stopping at index four excludes the element at index four, which is fifty. The elements at indexes one, two, and three are twenty, thirty, and forty, so the resulting list contains exactly those three values.

Why this answer

List slicing takes a start index that is included and a stop index that is excluded. With values[1:4], the slice begins at the element twenty and continues through the elements at indexes two and three, which are thirty and forty. The element at index four is not included because the stop bound is exclusive, so the result list holds three elements.

Exam trap

The trap here is treating the second slice index as inclusive, which shifts the result by one element and changes both the start and stop boundaries.

474
MCQeasy

A developer needs to determine the number of elements in a tuple named 't'. Which code snippet will correctly return the length?

A.t.append(5)
B.t[0] = 5
C.len(t)
D.t.pop()
AnswerC

`len(t)` returns the tuple's element count directly, satisfying the requirement to determine how many items `t` holds. Tuples implement `__len__`, so `len()` works on them exactly as on lists or strings, yielding the integer length without modifying the immutable tuple.

Why this answer

The correct way to determine the number of elements in a tuple in Python is to use the built-in `len()` function, which returns the length (number of items) of any sequence or collection, including tuples. Option C is correct because `len(t)` directly gives the count of elements in tuple `t`.

Exam trap

The PCEP exam often tests the immutability of tuples by presenting list-specific methods (like `append`, `pop`, or item assignment) as distractors, knowing that candidates may confuse tuples with lists.

How to eliminate wrong answers

Option A is wrong because `t.append(5)` attempts to call the `append()` method, which is available for lists but not for tuples; tuples are immutable and do not have an `append()` method, so this would raise an AttributeError. Option B is wrong because `t[0] = 5` tries to assign a new value to an index of a tuple, which is not allowed since tuples are immutable; this would raise a TypeError. Option D is wrong because `t.pop()` attempts to call the `pop()` method, which is available for lists but not for tuples; tuples are immutable and do not have a `pop()` method, so this would raise an AttributeError.

475
MCQmedium

A Python script contains the following code: x = 0.1 + 0.2 y = 0.3 print(x == y) What is printed?

A.0.3
B.True
C.False
D.An error occurs because floats cannot be compared with ==.
AnswerC

Due to binary floating-point representation, 0.1 and 0.2 cannot be stored exactly, and their sum is slightly more than 0.3. The literal 0.3 is also stored as a slightly different approximation. Therefore, the equality comparison returns False, and the program prints False.

Why this answer

Floating-point numbers in Python follow the IEEE 754 standard, so decimal values like 0.1, 0.2, and 0.3 are stored as approximations. Adding 0.1 and 0.2 yields a result that is not exactly equal to the stored approximation of 0.3. Consequently, the equality check returns False.

Exam trap

The trap here is assuming that decimal arithmetic behaves exactly as it does in mathematics, overlooking the binary floating-point representation that causes tiny rounding errors.

476
MCQmedium

Consider the following code: def foo(x, y): return x * y result = foo(y=2, 3) What is the error?

A.The function requires at least one argument but none provided.
B.A positional argument follows a keyword argument.
C.Keyword arguments cannot be used in function calls.
D.The function definition has too many parameters.
AnswerB

Python evaluates arguments left to right, so once y=2 is supplied as a keyword argument, the following positional 3 cannot be matched to a parameter. Python raises a SyntaxError because a positional argument follows a keyword argument.

Why this answer

In Python, when calling a function, all positional arguments must appear before any keyword arguments. The call `foo(y=2, 3)` violates this rule by placing a positional argument (`3`) after a keyword argument (`y=2`), which raises a SyntaxError. This is enforced by Python's parser to avoid ambiguity in argument binding.

Exam trap

The PCEP exam often tests the rule that positional arguments must precede keyword arguments in a function call, and the trap here is that candidates may mistakenly think the error is about missing arguments or invalid keyword usage, rather than the ordering violation.

How to eliminate wrong answers

Option A is wrong because the function call does provide arguments (a keyword argument `y=2` and a positional argument `3`), so the error is not about missing arguments. Option C is wrong because keyword arguments are fully supported in Python function calls and are commonly used for clarity and optional parameters. Option D is wrong because the function definition `def foo(x, y)` has exactly two parameters, which matches the number of arguments provided; the error is in the call syntax, not the definition.

477
MCQhard

What is the result of the expression: (1 and 0) or (not False and True)?

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

Python evaluates `and` before `or`, so `(1 and 0)` yields 0 and `(not False and True)` yields True. The `or` then returns True because one operand is truthy, satisfying the expression's requirement for a Boolean result.

Why this answer

1 and 0 evaluates to 0 (falsy). not False evaluates to True, so not False and True evaluates to True. 0 or True evaluates to True (the last truthy value).

478
MCQmedium

A programmer needs to swap the values of two variables a and b without using a temporary variable. Which approach works in Python?

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

Python evaluates the right-hand tuple (b, a) fully before assigning to the left-hand targets, so both original values are captured prior to rebinding. This tuple-unpacking swap needs no temporary variable and works for any assignable targets.

Why this answer

Python supports tuple unpacking, which allows the values of a and b to be swapped in a single atomic operation: a, b = b, a. This works by creating a tuple (b, a) on the right-hand side, then unpacking it into the variables on the left, effectively swapping the values without a temporary variable.

Exam trap

Python Institute often tests the misconception that simple sequential assignment (a = b; b = a) works for swapping, leading candidates to overlook Python's tuple unpacking mechanism.

How to eliminate wrong answers

Option A is wrong because a = b; b = a first overwrites a with b's value, then assigns the new a (which is now b) to b, so both variables end up with the original b value, failing to swap. Option C is wrong because while a = a ^ b; b = a ^ b; a = a ^ b works in languages like C with mutable integers, Python's integers are immutable and the XOR operation on integers does not modify variables in place; the code would actually work in Python due to rebinding, but it is not a recommended or readable approach and can fail with large integers due to Python's arbitrary precision. Option D is wrong because a = b + a; b = a - b; a = a - b works only if the sum does not overflow, but Python integers are arbitrary precision so overflow is not an issue; however, this approach is fragile with floating-point numbers and is not the idiomatic Python way.

479
Multi-Selecthard

Which three of the following statements about lists are true? (Choose three.)

Select 3 answers
A.Lists can be indexed with integers.
B.Lists can be sliced to create a new list.
C.Lists are mutable.
D.Lists have a fixed size once created.
E.Lists can only contain elements of the same data type.
AnswersA, B, C

Indexing starts at 0.

Why this answer

Lists in Python are ordered sequences that support indexing with integers, starting from 0 for the first element and negative integers for reverse indexing. This allows direct access to any element by its position, a fundamental feature of sequence types in Python.

Exam trap

Python Institute often tests the misconception that lists are fixed-size or homogeneous, similar to arrays in other languages, to catch candidates who confuse Python lists with static arrays or typed collections.

480
MCQeasy

Which of the following is NOT a valid variable name in Python?

A._myvar
B.myVar2
C.2nd_var
D.my_var
AnswerC

Python identifiers cannot begin with a digit, so 2nd_var raises a SyntaxError at parse time. Valid names must start with a letter or underscore, then contain letters, digits or underscores, making this the only invalid option.

Why this answer

Python variable names cannot start with a digit. The name '2nd_var' begins with '2', which violates Python's identifier naming rules. Valid variable names must start with a letter (a-z, A-Z) or an underscore (_), and can be followed by letters, digits, or underscores.

Exam trap

The PCEP exam often tests the rule that variable names cannot start with a digit, knowing that candidates may mistakenly think digits are allowed anywhere or that underscores are not valid starting characters.

How to eliminate wrong answers

Option A is wrong because '_myvar' is a valid variable name; it starts with an underscore, which is allowed, and contains only letters and underscores. Option B is wrong because 'myVar2' is valid; it starts with a letter and contains letters and digits, which is permitted. Option D is wrong because 'my_var' is valid; it starts with a letter and uses an underscore, both of which are allowed in Python identifiers.

481
MCQmedium

What is the output of the following code? print('Hello', 'World', sep='-', end='!\n')

A.Hello-World\n
B.Hello-World!\n
C.Hello World!\n
D.Hello World!\n
AnswerB

The `sep='-'` argument replaces the default space between the two string arguments, joining them as `Hello-World`, while `end='!\n'` substitutes the default newline terminator with an exclamation mark followed by a newline. Both keyword arguments therefore take effect, producing exactly `Hello-World!` plus a line break.

Why this answer

The `print()` function with `sep='-'` replaces the default space separator with a hyphen between the two arguments 'Hello' and 'World', producing 'Hello-World'. The `end='!\n'` parameter overrides the default newline-only end with an exclamation mark followed by a newline, so the output ends with '!' before the newline. Therefore, the correct output is 'Hello-World!\n'.

Exam trap

The trap here is that candidates often overlook the `end` parameter override and assume the default newline-only ending, or they confuse `sep` with `end`, leading them to pick an option with a space separator or missing the exclamation mark.

How to eliminate wrong answers

Option A is wrong because it omits the exclamation mark specified by `end='!\n'`, showing only the default newline. Option C is wrong because it uses a space separator instead of the hyphen specified by `sep='-'`. Option D is wrong for the same reason as C (space instead of hyphen) and also omits the exclamation mark.

482
Multi-Selectmedium

A developer is creating a Python script and needs to assign a value to a variable. Which TWO of the following assignment statements are syntactically valid in Python? (Choose two.)

Select 2 answers
A.my-var = 10
B.my var = 10
C.my_var2 = 10
D.2myvar = 10
E.my_var = 10
AnswersC, E

This is valid: 'my_var2' starts with a letter, contains an underscore and a digit after the first character. Digits are allowed after the first character. The assignment sets my_var2 to 10. This is syntactically correct and demonstrates a common naming pattern.

Why this answer

Valid Python identifiers must start with a letter or underscore, and may contain letters, digits, and underscores. 'my_var = 10' and 'my_var2 = 10' follow these rules. Names starting with a digit, containing a hyphen, or containing a space are invalid and cause SyntaxError.

Exam trap

The trap here is assuming that digits can appear anywhere or that hyphens and spaces are allowed, but only letters, digits, and underscores are permitted after the first character.

Page 6

Page 7 of 7

All pages

Certified Entry-Level Python Programmer PCEP PCEP Questions 451–482 | Page 7/7 | Courseiva