Courseiva

Certified Entry-Level Python Programmer PCEP (PCEP) — Questions 151–225

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

Page 2

Page 3 of 7

Page 4
151
MCQmedium

A developer writes a function that attempts to access a dictionary key that may not exist: def get_value(data, key): try: return data[key] except KeyError: return None. They call it as get_value({'a': 1}, 'b'). What is the result and why?

A.The function returns 1 because it falls back to the first available key.
B.The function returns the string 'KeyError' because the exception is converted to a string.
C.None is returned because the KeyError is caught and handled.
D.A KeyError is raised because the key 'b' is not in the dictionary.
AnswerC

When data[key] is evaluated and the key 'b' is not found, a KeyError is raised. The except KeyError block catches this specific exception and executes its body, which returns None. The function then exits normally. This demonstrates how exception handling can provide a fallback value instead of crashing. The caller receives None as the result.

Why this answer

The function uses a try-except block to handle a potential KeyError. When the key 'b' is not found, the exception is caught, and the except block returns None. This provides a safe way to access dictionary values without causing the program to crash.

The caller receives None as the result of the function call.

Exam trap

The trap here is forgetting that the except block handles the exception, so no error is raised to the caller.

152
MCQmedium

A software tester is examining a list of error codes: `errors = [404, 500, 403, 404, 200]`. She wants to determine if the code 404 appears in the list and print 'Found' if it does, otherwise 'Not found'. Which code correctly achieves this?

A.if errors.count(404) == 0: print('Found') else: print('Not found')
B.if errors in 404: print('Found') else: print('Not found')
C.if 404 in errors: print('Found') else: print('Not found')
D.if errors.index(404): print('Found') else: print('Not found')
AnswerC

The `in` operator checks membership in a list. If 404 is present, it prints 'Found'; otherwise, 'Not found'. Since 404 is in the list, it prints 'Found'. This is the simplest and most direct way to test for presence.

Why this answer

The `in` operator is the correct tool for checking if an element exists in a list. It returns a boolean and does not raise errors. The other options either misuse the `in` operator, rely on `index()` which can raise exceptions and misinterpret index 0, or invert the logic with `count()`.

Exam trap

The trap here is using `index()` or `count()` for membership testing, which can lead to incorrect results or exceptions when the value is at index 0 or absent.

153
MCQhard

A monitoring script checks a list of sensor readings and must stop examining them as soon as a reading above 100 is found, without checking any remaining readings. The readings list contains at least one value above 100. Which loop control approach implements this behavior correctly?

A.Use pass when a reading exceeds 100, so the loop silently ignores the condition and finishes normally.
B.Use continue when a reading exceeds 100, so the loop skips the rest of that iteration and keeps going.
C.Use break when a reading exceeds 100, so the loop ends immediately and no further readings are checked.
D.Use else on the for loop, so the loop stops when a reading exceeds 100.
AnswerC

break terminates the innermost enclosing loop at once, so as soon as a reading greater than 100 appears, no subsequent readings are examined. That exactly matches the requirement to stop early. Execution resumes at the first statement after the loop, where the script can act on the detected condition.

Why this answer

Only break exits a loop immediately when a condition is met. When a reading above 100 is encountered, break ends iteration and control moves past the loop, so no later readings are examined. The other keywords either skip one iteration, do nothing, or run after normal completion.

Exam trap

The trap here is treating continue as a way to stop the loop, when it only skips the current iteration and keeps iterating.

154
MCQmedium

What is the output of the following code? print(3 * 'ab' + 'c')

A.'abababc'
B.'ababc'
C.TypeError
D.'ababab c'
AnswerA

String repetition binds tighter than concatenation, so `3 * 'ab'` evaluates first, yielding `'ababab'`. The `+` operator then joins that result with `'c'`, producing `'abababc'`. This satisfies the stem's single print statement, where no parentheses alter the default left-to-right precedence of `*` over `+`.

Why this answer

The expression `3 * 'ab' + 'c'` first multiplies the string `'ab'` by 3, resulting in `'ababab'` (string repetition), and then concatenates `'c'` using the `+` operator, producing `'abababc'`. In Python, the `*` operator on a string and an integer repeats the string that many times, and `+` concatenates strings.

Exam trap

Python Institute often tests the order of operations and the fact that `*` binds tighter than `+` in Python, leading candidates to mistakenly think the expression is evaluated as `3 * ('ab' + 'c')` or to forget that string repetition produces a single concatenated string without separators.

How to eliminate wrong answers

Option B is wrong because `'ababc'` would result from `2 * 'ab' + 'c'`, not from multiplying by 3. Option C is wrong because both operations are valid on strings in Python; no TypeError occurs. Option D is wrong because string concatenation does not insert a space; the output is `'abababc'` without any space before `'c'`.

155
MCQeasy

A junior developer is writing a script to read a number from input and double it. They write: num = input("Enter a number: ") result = num * 2 print(result) When they test with input 5, the output is '55' instead of 10. What is wrong?

A.There is a syntax error in the multiplication line.
B.The print function is incorrectly formatting the output.
C.The variable name 'num' conflicts with a built-in function.
D.The input is treated as a string; they need to convert it to int.
AnswerD

The built-in `input()` function always returns a string, so `num * 2` performs string repetition rather than arithmetic multiplication, producing `'55'`. Wrapping the call as `int(input("Enter a number: "))` converts the value to an integer, satisfying the requirement to double the numeric input and print `10`.

Why this answer

The `input()` function in Python always returns a string, even if the user types a number. When you use the `*` operator on a string, it repeats the string, so `'5' * 2` yields `'55'`. To perform numeric multiplication, you must convert the input to an integer using `int(input(...))`.

Exam trap

The trap here is that candidates often assume `input()` returns a number because the user typed digits, but Python treats all keyboard input as a string, and the `*` operator's string repetition behavior is a classic PCEP trick.

How to eliminate wrong answers

Option A is wrong because there is no syntax error; the line `result = num * 2` is syntactically valid Python. Option B is wrong because the `print()` function is correctly outputting the value of `result`; the issue is the value itself, not the formatting. Option C is wrong because `num` is not a built-in function name; built-in functions like `int`, `float`, `str` are reserved, but `num` is a free variable name.

156
Multi-Selecteasy

Which TWO of the following expressions produce the integer 5?

Select 2 answers
A."5"
B.10 // 2
C.int(5.7)
D.5.0
E.10 / 2
AnswersB, C

The floor division operator // divides and rounds down to the nearest integer, so 10 // 2 evaluates to the integer 5, not the float 5.0. This satisfies the stem's requirement of producing the integer 5, unlike true division / which would return 5.0.

Why this answer

Option B, 10 // 2, is correct because the // operator performs floor division on integers, and 10 divided by 2 yields exactly 5 as an int. Option C, int(5.7), is correct because int() truncates the float toward zero, discarding the fractional part .7 and returning the integer 5. Option A, "5", is a string literal, not an integer, so it does not produce the integer 5.

Option D, 5.0, is a floating-point value, not an int. Option E, 10 / 2, uses true division, which in Python 3 returns the float 5.0 rather than the integer 5.

Exam trap

Python Institute often tests the distinction between `/` (true division returning float) and `//` (floor division returning int), as well as the difference between numeric types (int vs. float vs. string), to catch candidates who overlook Python's implicit type conversions.

157
MCQmedium

A developer wants to read a floating-point number from user input and compute its square. Which code snippet correctly accomplishes this?

A.num = input(); result = num * num
B.num = float(input()); result = num ** 2
C.result = input() ** 2
D.num = int(input()); result = num ** 2
AnswerB

float() converts the input string to a floating-point number, satisfying the requirement to read a decimal value, and ** is Python's exponentiation operator, so num ** 2 computes the square. Using int() would truncate decimals, and string multiplication would repeat the text rather than square it.

Why this answer

It uses `float(input())` to convert the user's input (which is always a string) into a floating-point number, and then computes the square using the exponentiation operator `**`. This ensures that decimal values are handled correctly, which is required for computing the square of a floating-point number.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type, leading candidates to forget explicit conversion and choose options that attempt arithmetic on strings.

How to eliminate wrong answers

Option A is wrong because `input()` returns a string, and multiplying two strings with `*` performs string repetition, not numeric multiplication, so it will not compute the square of a number. Option C is wrong because `input()` returns a string, and the `**` operator cannot be applied to a string; this will raise a TypeError. Option D is wrong because `int(input())` converts the input to an integer, which truncates any decimal part, so it cannot correctly handle floating-point numbers as required.

158
Multi-Selectmedium

Which TWO of the following expressions evaluate to True in Python? (Choose two.)

Select 2 answers
A.1 == True
B.0 == False
C.'0' == 0
D.2 == True
E.None == False
AnswersA, B

Python's bool type subclasses int, so True equals the integer 1 in comparisons. The equality operator checks numeric value rather than identity, making 1 == True evaluate to True. This satisfies the stem's requirement for expressions returning True.

Why this answer

Option A (1 == True) is correct because Python's bool is a subclass of int, so True has the integer value 1 and the equality comparison returns True. Option B (0 == False) is correct for the same reason: False has the integer value 0, so comparing it to 0 yields True. Option C ('0' == 0) is not correct because a str and an int are different types and are never equal in Python.

Option D (2 == True) is not correct because True equals 1, not 2. Option E (None == False) is not correct because None is a distinct object that is only equal to None, not to False.

Exam trap

Python Institute often tests the misconception that `True` and `False` are completely separate from integers, leading candidates to incorrectly reject options A and B, or to mistakenly believe that `'0'` or `None` are falsy enough to equal `0` or `False`.

159
MCQmedium

A function is defined as: def add(a, b=5): return a + b What is the result of add(10)?

A.10
B.5
C.15
D.Error
AnswerC

The parameter b uses its default value of 5 because only one argument is supplied, so the call evaluates 10 + 5, returning 15. Python applies default arguments when the corresponding positional argument is omitted.

Why this answer

The function `add(a, b=5)` defines a default value of 5 for parameter `b`. When called as `add(10)`, the argument 10 is assigned to `a`, and `b` uses its default value of 5. The function returns `10 + 5 = 15`, making option C correct.

Exam trap

Python Institute often tests the misconception that default parameters are required or that omitting them causes an error, leading candidates to pick 'Error' (option D) when the function is actually called correctly with a single argument.

How to eliminate wrong answers

Option A is wrong because it assumes `b` is ignored or defaults to 0, but the default is 5, so the result is not 10. Option B is wrong because it suggests the function returns only the default value of `b`, ignoring the argument `a=10`. Option D is wrong because the function call `add(10)` provides exactly one required argument (`a`), and `b` has a default value, so no error occurs.

160
MCQmedium

A function is defined as: def min_max(nums): return min(nums), max(nums). What type of value does it return?

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

Returning comma-separated values from a function packs them into a single tuple, so `min_max` yields a two-element tuple containing the minimum and maximum. This satisfies the stem's requirement to identify the return type: the parentheses are optional, but the comma operator always constructs a tuple.

Why this answer

The function `min_max` uses `return min(nums), max(nums)`, which is a comma-separated list of expressions. In Python, when multiple values are returned separated by commas, they are automatically packed into a tuple. Therefore, the function returns a tuple containing the minimum and maximum values.

Exam trap

The PCEP exam often tests the misconception that multiple return values are returned as a list or that parentheses are required to create a tuple, but in Python, it is the comma that defines a tuple, not the parentheses.

How to eliminate wrong answers

Option B is wrong because a set is created with curly braces or the `set()` constructor, and returning values separated by commas does not produce a set. Option C is wrong because a dictionary requires key-value pairs, but the function returns two values without any keys. Option D is wrong because a list is created with square brackets, and the comma syntax in a return statement does not produce a list.

161
MCQeasy

During a lab exercise, a student writes the following code to print a countdown from 3 down to 1, but the code enters an infinite loop and never stops. The code is: count = 3 while count > 0: print(count) Which change makes the loop terminate after printing 3, 2, and 1?

A.Add the statement count = count + 1 inside the loop body.
B.Add the statement count = count - 1 inside the loop body.
C.Change the condition to while count < 0:
D.Add the statement count += 0 inside the loop body.
AnswerB

Decrementing count each pass changes the value from 3 to 2 to 1, and after printing 1 it becomes 0, making count > 0 false and ending the loop. This is the standard counter-controlled pattern, where the loop variable must be updated inside the body so the condition eventually fails and the program continues.

Why this answer

A while loop repeats as long as its condition stays true, so the counter must move toward the exit value on each pass. Reducing count by one each iteration makes the sequence 3, 2, 1 and then 0, at which point the condition fails and execution continues after the loop. Without such an update the condition never changes.

Exam trap

The trap here is assuming the loop condition alone controls termination, when an unchanged loop variable leaves the condition permanently true.

162
MCQmedium

After 'x = 5; x += 3', what is the value of x?

A.5
B.8
C.3
D.15
AnswerB

The augmented assignment x += 3 is equivalent to x = x + 3. With x initially 5, the expression evaluates to 8, which is stored back into x. The variable therefore holds 8 after execution.

Why this answer

The compound assignment operator `+=` adds the right operand to the current value of the variable and assigns the result back. Starting with `x = 5`, the statement `x += 3` is equivalent to `x = x + 3`, which computes `5 + 3 = 8` and stores it in `x`.

Exam trap

The trap here is that candidates often confuse `+=` with simple assignment or with other operators like `*=` or `=`, leading them to pick the original value, the right operand alone, or a product instead of the sum.

How to eliminate wrong answers

Option A is wrong because it suggests the value remains 5, ignoring that `+=` performs an addition and reassignment. Option C is wrong because it incorrectly treats `+=` as a simple assignment of the right operand (3) rather than an addition operation. Option D is wrong because it implies multiplication (5 * 3 = 15), confusing `+=` with `*=` or another operator.

163
Drag & Dropmedium

Arrange the steps to install a third-party Python package using pip.

Drag or tap steps into the slots.

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

Why this order

Installing packages with pip involves checking pip, running install, and verifying.

164
MCQmedium

A company uses a for loop to iterate over a list of transaction amounts. They want to skip negative amounts. Which statement inside the loop correctly achieves this?

A.if amount < 0: amounts.remove(amount)
B.if amount < 0: break
C.if amount < 0: pass
D.if amount < 0: continue
AnswerD

The continue statement immediately ends the current iteration and returns control to the loop header, so the negative amount is never processed. Placing it under 'if amount < 0' skips only negative values while all non-negative amounts still execute.

Why this answer

The `continue` statement immediately jumps to the next iteration of the loop, skipping any remaining code in the current iteration. When `amount < 0`, the loop will not process that negative transaction and will move to the next element in the list, effectively skipping negative amounts.

Exam trap

Python Institute often tests the distinction between `break`, `continue`, and `pass`, and the trap here is that candidates confuse `break` (which exits the loop) with `continue` (which skips to the next iteration), or think `pass` is a valid way to skip code when it actually does nothing.

How to eliminate wrong answers

Option A is wrong because `amounts.remove(amount)` modifies the list while iterating over it, which can lead to skipped elements or index errors due to the list's size changing during iteration. Option B is wrong because `break` terminates the entire loop prematurely, stopping all further iteration even for positive amounts after the first negative one. Option C is wrong because `pass` is a no-op that does nothing; it simply continues execution to the next line, so negative amounts would still be processed.

165
Multi-Selectmedium

Which THREE of the following are valid ways to create a list with elements 10, 20, 30?

Select 3 answers
A.my_list = [x for x in (10,20,30)]
B.my_list = list((10, 20, 30))
C.my_list = list(10, 20, 30)
D.my_list = [10; 20; 30]
E.my_list = [10, 20, 30]
AnswersA, B, E

The list comprehension iterates over the tuple (10,20,30) and appends each element, producing a new list containing exactly those three values. It is a valid construction, though more verbose than a literal, and yields the required elements in order.

Why this answer

Option A is correct because a list comprehension iterating over the tuple (10,20,30) produces a new list [10, 20, 30]. Option B is correct because list((10, 20, 30)) converts the tuple into a list with those three elements. Option E is correct because a list literal [10, 20, 30] directly creates the desired list.

Option C is invalid because list() accepts at most one iterable argument, so list(10, 20, 30) raises a TypeError. Option D is invalid because semicolons are not valid separators inside a Python list literal; elements must be comma-separated.

Exam trap

In multi-select questions, carefully evaluate each option against the stem without reading in extra constraints. The question simply asks for valid ways to create a specific list; do not assume that a literal assignment is excluded unless explicitly stated. Be cautious about the number of correct answers: ensure you select all that apply, especially when the stem specifies a count.

166
MCQmedium

A developer is writing a Python script and assigns a value to a variable named '2nd_place'. When the script is run, it raises a SyntaxError. What is the cause of this error?

A.Variable names must be uppercase.
B.Variable names cannot start with a digit.
C.The name '2nd_place' is a reserved keyword.
D.Variable names cannot contain underscores.
AnswerB

In Python, identifiers must begin with a letter (a-z, A-Z) or an underscore, not a digit. '2nd_place' starts with '2', which is invalid. This rule prevents ambiguity with numeric literals. The interpreter cannot parse '2nd_place' as a single token, so it raises a SyntaxError at the point of assignment.

Why this answer

Python identifiers must start with a letter or underscore, not a digit. The name '2nd_place' begins with '2', so the parser cannot treat it as a single identifier and raises a SyntaxError. Underscores are allowed, uppercase is not required, and the name is not a keyword.

Exam trap

The trap here is focusing on the underscore or the word 'place' instead of the leading digit, which is the actual syntax violation.

167
MCQeasy

A Python developer is writing a function that takes a tuple of numbers and returns a new tuple containing only the even numbers. They write the following code: def filter_even(numbers): result = () for num in numbers: if num % 2 == 0: result += (num,) return result What is the primary reason this function works correctly?

A.Tuples support the append method, which adds elements to the end of the tuple in place.
B.Tuples are immutable, but the += operator creates a new tuple each time, which is then reassigned to result.
C.The += operator modifies the tuple in place by adding the new element to the existing tuple object.
D.The function returns a list, not a tuple, because += converts the tuple to a list.
AnswerB

The `+=` operator on a tuple does not modify the original tuple in place because tuples are immutable. Instead, it creates a new tuple by concatenating the existing tuple with the new element, then rebinds the variable `result` to this new tuple. This allows the function to accumulate even numbers correctly, as each iteration produces a new tuple.

Why this answer

The function correctly builds a tuple of even numbers because the `+=` operator, when used with tuples, creates a new tuple by concatenation and reassigns it to the variable. Tuples are immutable, so this is the only way to 'modify' them. The other options incorrectly describe tuple immutability or methods.

Exam trap

The trap here is thinking that tuples can be modified in place or that they have methods like `append`, but they are immutable and only support concatenation.

168
MCQeasy

You are a junior developer at a small startup. Your team has a Python script that automates daily data processing. The script reads a CSV file, processes each row, and writes results to a new file. Recently, the script started crashing with a 'ValueError: invalid literal for int()' error. The error occurs on a line that converts a field to an integer using int() on a string value. The CSV file comes from an external source that sometimes contains non-numeric values like 'N/A' or empty strings. Which course of action is best to handle this robustly without stopping the entire process?

A.Wrap the conversion in a try-except block and handle the exception appropriately for each row.
B.Add logging before the conversion to print the problematic value.
C.Use a regex to replace all non-digit characters before conversion.
D.Contact the external source to ensure no missing values are sent.
AnswerA

A try-except around int() catches ValueError for each non-numeric field such as 'N/A' or empty strings, letting the loop skip or substitute that row and continue. This satisfies the requirement to handle bad data robustly without stopping the entire process.

Why this answer

Wrapping the conversion in a try-except block allows the script to catch the ValueError for each row individually, log or handle the problematic row (e.g., skip it or use a default value), and continue processing the remaining rows without crashing. This is the standard Pythonic approach for handling expected but unpredictable data quality issues in external input, as it separates error handling from the main logic and preserves the robustness of the batch process.

Exam trap

The PCEP exam often tests the misconception that logging or pre-processing (like regex) is sufficient to prevent runtime errors, when in fact only exception handling can gracefully recover from an exception that has already been raised.

How to eliminate wrong answers

Option B is wrong because adding logging before the conversion only prints the problematic value but does not prevent the ValueError from being raised, so the script will still crash on the first invalid row. Option C is wrong because using a regex to replace all non-digit characters (e.g., removing 'N/A' entirely) could silently corrupt data (e.g., turning '123-456' into '123456' or removing valid negative signs) and does not handle empty strings or other non-numeric formats robustly. Option D is wrong because contacting the external source is a long-term process improvement, not an immediate fix; it does not handle the current crashing script and assumes the source can always provide clean data, which is unrealistic in production.

169
MCQeasy

A developer writes a function that assigns a new value to an element of a list passed as an argument. After the function returns, the caller observes that the original list has been modified. The developer wants a second function that appends an item to a list but leaves the caller's list unchanged. Which definition achieves this?

A.def add_item(lst, item): lst = lst + [item] return lst
B.def add_item(lst, item): lst += [item] return lst
C.def add_item(lst, item): lst.insert(0, item) return lst
D.def add_item(lst, item): lst.append(item) return lst
AnswerA

The expression lst + [item] creates a brand-new list object and rebinds the local name lst to it. The caller's original list object is never mutated, so after the function returns the caller still sees the unchanged list. The new list is returned for the caller to use if desired, which satisfies the requirement of appending without affecting the caller's list.

Why this answer

Passing a list to a function passes a reference to the same object, so any in-place method such as append, insert, or += alters the caller's data. Only creating a new list object, as with the concatenation lst + [item], avoids mutating the caller's list while still producing an appended result that can be returned.

Exam trap

The trap here is assuming that any assignment inside a function, including augmented assignment on a list parameter, creates a local copy and therefore protects the caller's object.

170
MCQeasy

You are maintaining a Python script that calculates team bonuses based on sales data. The script reads a dictionary where keys are employee names and values are total sales (float). It then applies a 10% bonus if sales exceed 5000. The code snippet is: def calculate_bonus(sales): for name, value in sales.items(): if value > 5000: print(f"{name} gets bonus") However, the manager wants the script to return a list of employees who qualify, not just print them. They also want to avoid side effects. What is the best way to modify this function?

A.Create a global list variable at the top of the script and append each qualifying name to it.
B.Keep the function as is and have the caller capture the printed names by redirecting stdout.
C.Use the dictionary's update method to mark bonus status in the original sales dictionary.
D.Build a list inside the function and return it at the end.
AnswerD

Building a list inside the function and returning it satisfies both constraints: it replaces printing with a returned value, and it avoids side effects by keeping all state local. Appending each qualifying name during iteration, then returning the list, gives the manager the required collection without mutating external state.

Why this answer

It modifies the function to build a list of qualifying employee names inside the function and returns that list. This avoids side effects (no global variables, no mutation of the input dictionary) and follows the principle of returning results rather than printing them, making the function reusable and testable.

Exam trap

The PCEP exam often tests the concept of side effects versus pure functions, and the trap here is that candidates may think mutating the input dictionary (Option C) or using a global variable (Option A) are acceptable, when in fact they violate the principle of avoiding side effects and reduce code maintainability.

How to eliminate wrong answers

Option A is wrong because using a global list introduces side effects and makes the function non-reentrant and harder to debug; it also violates the principle of avoiding global state. Option B is wrong because capturing stdout is a fragile workaround that does not actually return data and still relies on the function's side effect of printing; it also adds unnecessary complexity and breaks if output is redirected. Option C is wrong because using the dictionary's update method to mark bonus status mutates the original sales dictionary, which is a side effect that can cause unexpected behavior in other parts of the script and violates the requirement to avoid side effects.

171
MCQeasy

A Python script contains the following code: num = 7 result = num ** 2 print(result) What is the output?

A.Error: unsupported operand type(s)
B.49
C.7
D.14
AnswerB

The ** operator in Python performs exponentiation. Here, num ** 2 raises 7 to the power of 2, which equals 49. Therefore, the print statement outputs 49. This is the correct behavior for the exponentiation operator, which is a fundamental arithmetic operator in Python.

Why this answer

The exponentiation operator ** raises the left operand to the power of the right operand. With num assigned 7, num ** 2 computes 7 squared, which is 49. The other options misinterpret the operator as multiplication, no operation, or an error, but none of those apply because both operands are integers and the operator is valid.

Exam trap

The trap here is confusing the exponentiation operator ** with the multiplication operator *, which would produce 14 instead of 49.

172
Matchingmedium

Match each Python data type to its description.

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

Concepts
Matches

Whole numbers, e.g., 42

Numbers with decimal point, e.g., 3.14

Sequence of characters, e.g., 'hello'

Logical values True or False

Ordered, mutable collection of items

Why these pairings

The correct matches are: A (int - whole numbers), B (float - numbers with decimal point), D (bool - Boolean values True or False). Option C (str) is incorrect because strings are immutable sequences of characters, not mutable collections. Option E (list) is incorrect because lists are mutable collections, not immutable sequences.

Option F (tuple) is incorrect because tuples are immutable sequences, not mutable collections.

173
MCQeasy

Which of the following expressions evaluates to False?

A.2 != 1
B.10 == 10
C.3 >= 4
D.5 < 10
AnswerC

The expression 3 >= 4 evaluates to False because the greater-than-or-equal-to operator requires the left operand to be numerically larger than or identical to the right. Since 3 is strictly less than 4, the comparison fails, satisfying the stem's requirement for an expression that returns False.

Why this answer

(3 >= 4) evaluates to False because the 'greater than or equal to' operator (>=) returns True only if the left operand is greater than or equal to the right operand. Since 3 is neither greater than nor equal to 4, the expression is False.

Exam trap

Python Institute often tests whether candidates confuse the direction of comparison operators (e.g., mistaking >= for <=) or forget that >= includes equality, leading them to incorrectly assume 3 >= 4 is True.

How to eliminate wrong answers

Option A is wrong because 2 != 1 uses the inequality operator (!=) and returns True since 2 is not equal to 1. Option B is wrong because 10 == 10 uses the equality operator (==) and returns True since both operands are equal. Option D is wrong because 5 < 10 uses the less-than operator (<) and returns True since 5 is indeed less than 10.

174
MCQeasy

A Python program needs to store the integer value 42 in a variable named count. Which line of code correctly assigns this value?

A.count == 42
B.42 = count
C.count = 42
D.count := 42
AnswerC

The single equals sign = is the assignment operator in Python. It binds the name count to the integer object 42. This is the standard and correct way to store a value in a variable, satisfying the requirement exactly.

Why this answer

The assignment operator = stores a value in a variable. In this scenario, count = 42 correctly binds the name count to the integer 42. The other options either compare, reverse the assignment, or use an operator that is not valid as a standalone statement.

Exam trap

The trap here is confusing the assignment operator = with the equality operator ==, which performs a comparison rather than storing a value.

175
MCQeasy

A company maintains a list of employee names. They want to check if 'Alice' is in the list. Which of the following is the most Pythonic way to achieve this?

A.employees.contains('Alice')
B.for name in employees: if name == 'Alice': found = True; break
C.if employees.index('Alice') != -1:
D.if 'Alice' in employees:
AnswerD

The 'in' operator performs a membership test directly against the list, returning a Boolean without indexing or looping. Writing 'if "Alice" in employees:' is the idiomatic, readable Pythonic form, avoiding alternatives like index() or manual iteration that add unnecessary complexity.

Why this answer

The most Pythonic way because it uses the `in` operator, which directly checks membership in a list with a single, readable expression. This approach is idiomatic Python, leveraging the language's built-in support for membership testing without manual iteration or exception handling.

Exam trap

Python Institute often tests the distinction between Python's `in` operator and methods from other languages (like `contains()`), or the incorrect assumption that `.index()` returns -1 on failure, which is a common trap for candidates coming from languages like Java or C++.

How to eliminate wrong answers

Option A is wrong because Python lists do not have a `contains()` method; this is a Java-style method name, not valid in Python. Option B is wrong because while the loop works, it is verbose and non-idiomatic; Python's `in` operator is the preferred, concise way to test membership. Option C is wrong because `list.index()` raises a `ValueError` if the item is not found, not returning -1; using it for membership testing is both incorrect and inefficient.

176
MCQmedium

A programmer is writing a script to process a list of sensor readings. The script should stop processing as soon as a reading of 0 is encountered. Which statement should be placed inside the loop to achieve this?

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

The `break` statement immediately terminates the innermost enclosing loop. When a sensor reading of 0 is detected, using `break` will exit the loop entirely, preventing further processing of remaining readings. This matches the requirement to stop processing as soon as the condition is met.

Why this answer

To stop a loop immediately when a condition is met, the `break` statement is used. It transfers control to the statement immediately following the loop. The `continue` statement would only skip the current iteration, while `pass` does nothing and `exit` is not a valid loop control statement.

Exam trap

The trap here is confusing `break` with `continue`; `break` exits the loop entirely, while `continue` only skips the current iteration.

177
MCQhard

What is the output of print(type(3 + 4.5))?

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

Adding an int and a float triggers Python's implicit numeric promotion, converting the integer operand to float before addition. The result, 7.5, is therefore a float object, and type() returns <class 'float'>. This satisfies the stem's requirement to identify the exact type of the mixed-type arithmetic expression.

Why this answer

In Python, when you add an integer (3) and a float (4.5), implicit type conversion (coercion) occurs: the integer is promoted to a float to avoid data loss. The result is 7.5, which is a float. Therefore, type(7.5) returns <class 'float'>.

Exam trap

Python Institute often tests the misconception that integer + float yields an integer, or that the type() function returns the string 'int' or 'float' rather than the actual class object.

How to eliminate wrong answers

Option A is wrong because the result of adding an int and a float is not an int; Python does not truncate or round the result to an integer. Option B is wrong because the result is not a complex number; complex numbers require an imaginary part (e.g., 3+4j). Option D is wrong because the result is a numeric value, not a string; the print function outputs the type object as a string representation, but the underlying type is float.

178
MCQmedium

A programmer is building a simple inventory tracker using a Python list named stock that contains integer quantities. They need to add 10 to every quantity in the list, modifying the list in place. Which code correctly performs this operation?

A.stock = [qty + 10 for qty in stock]
B.stock = stock + 10
C.for qty in stock: qty = qty + 10
D.for i in range(len(stock)): stock[i] = stock[i] + 10
AnswerD

Iterating over indices with range(len(stock)) allows direct assignment to each element via stock[i], which modifies the list in place. This is the standard pattern for updating every element when you need to change the original list. The other approaches either do not modify the list or produce incorrect results.

Why this answer

To modify a list in place, you must assign to individual elements using their indices. Using range(len(stock)) provides those indices, and stock[i] = stock[i] + 10 updates each element. The other options either leave the list unchanged, create a new list, or cause an error, so they do not satisfy the in-place requirement.

Exam trap

The trap here is assuming that modifying the loop variable modifies the list, when actually it only rebinds the variable to a new value.

179
MCQeasy

A user enters '42' at an input prompt. After executing x = input(), what is the type of x?

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

input() always returns a string regardless of what the user types, so entering 42 yields the characters '4' and '2' as a str. No implicit numeric conversion occurs; int() or float() must be called explicitly to obtain a number.

Why this answer

The `input()` function in Python always returns the user's input as a string, regardless of whether the input looks like a number. When the user enters '42', it is captured as the string '42', so the type of `x` is `str`. This is because `input()` does not perform any implicit type conversion.

Exam trap

The trap here is that candidates assume `input()` automatically converts numeric-looking input to an integer or float, because many other languages (like C++ with `cin`) do so, but Python's `input()` always returns a string.

How to eliminate wrong answers

Option A is wrong because `float` would only be the type if the code explicitly converted the input using `float(x)`, but `input()` alone returns a string. Option C is wrong because `bool` is never the default return type of `input()`; a boolean would require explicit conversion or a specific condition. Option D is wrong because `int` would require explicit conversion via `int(x)`; `input()` does not automatically parse numeric strings into integers.

180
Multi-Selecteasy

Which THREE of the following are valid ways to create a list in Python?

Select 3 answers
A.list((1, 2, 3))
B.[x for x in range(3)]
C.[1, 2, 3]
D.(1, 2, 3)
E.{1, 2, 3}
AnswersA, B, C

Passing a tuple to the `list()` constructor iterates its elements and builds a new list, yielding `[1, 2, 3]`. This satisfies the stem's requirement for a valid list-creation method, since `list()` accepts any iterable, including tuples, strings and ranges, not just list literals.

Why this answer

Option A, list((1, 2, 3)), is correct because the list() constructor accepts any iterable — here a tuple — and returns a new list object [1, 2, 3]. Option B, [x for x in range(3)], is correct because a list comprehension is a valid literal-style expression that builds a list, producing [0, 1, 2]. Option C, [1, 2, 3], is correct because it is a direct list display (literal) using square brackets, which is the most basic way to create a list.

Option D, (1, 2, 3), is not correct because parentheses with commas create a tuple, not a list. Option E, {1, 2, 3}, is not correct because curly braces create a set (or a dict if key-value pairs are used), not a list.

Exam trap

The PCEP exam often tests the distinction between list literals (`[]`), tuple literals (`()`), and set literals (`{}`), trapping candidates who confuse the syntax for creating a list with that of other sequence or collection types.

181
MCQeasy

Which of the following correctly creates a tuple with a single element 5?

A.t = (5,)
B.t = (5)
C.t = (5)
D.t = (5, 5)
AnswerA

Correct. The trailing comma is required to create a single-element tuple.

Why this answer

In Python, a tuple with a single element requires a trailing comma after the element. Without the comma, parentheses are treated as grouping operators for expression evaluation, not as a tuple literal. Thus, `t = (5,)` creates a tuple containing the integer 5.

Exam trap

The trap here is that candidates mistakenly believe parentheses alone create a tuple, overlooking the mandatory trailing comma for single-element tuples, which Cisco tests to distinguish between tuple creation and simple expression grouping.

How to eliminate wrong answers

Option B is wrong because `t = (5)` does not create a tuple; the parentheses are interpreted as grouping, so `t` becomes the integer 5. Option C is identical to B and also wrong for the same reason. Option D is wrong because `t = (5, 5)` creates a tuple with two elements, not a single element.

182
MCQeasy

A developer writes a function that takes a tuple as an argument and tries to modify an element inside the tuple. What happens?

A.The code raises a TypeError.
B.The tuple is converted to a list automatically.
C.The first element is modified successfully.
D.The code raises a ValueError.
AnswerA

Tuples are immutable, so any assignment to an index raises a TypeError at runtime. The interpreter blocks the modification rather than silently ignoring it, which satisfies the stem's scenario of attempting to change a tuple element.

Why this answer

Tuples in Python are immutable, meaning their elements cannot be changed after creation. Attempting to modify an element (e.g., `my_tuple[0] = 5`) raises a `TypeError` because the tuple object does not support item assignment. This is a fundamental property of the tuple data type.

Exam trap

Python Institute often tests the distinction between `TypeError` and `ValueError` — the trap here is that candidates may confuse an operation that is not allowed (TypeError) with an operation that receives an invalid value (ValueError).

How to eliminate wrong answers

Option B is wrong because Python never automatically converts a tuple to a list when modification is attempted; such an operation simply raises an error. Option C is wrong because tuples are immutable, so no element can be modified successfully. Option D is wrong because a `ValueError` is raised for inappropriate values, not for operations that are not supported by the object type; the error here is a `TypeError`.

183
MCQhard

Which exception is raised when trying to access a dictionary key that does not exist?

A.KeyError
B.TypeError
C.ValueError
D.AttributeError
AnswerA

Accessing a missing dictionary key raises KeyError, satisfying the stem's requirement for the exception triggered by absent keys. Python's dict lookup invokes `__getitem__`, which raises KeyError rather than returning a default, unlike `get()`. This distinguishes it from IndexError, used by sequences such as lists and tuples.

Why this answer

In Python, when you attempt to access a dictionary key that does not exist using square bracket notation (e.g., `my_dict['nonexistent']`), the interpreter raises a `KeyError`. This is the standard exception for missing dictionary keys, as defined in the Python language specification. The correct answer is A.

Exam trap

Python Institute often tests whether candidates confuse `KeyError` with `ValueError` or `TypeError`, especially when the question involves dictionary operations like `pop()` or `del` on a missing key, where the same `KeyError` is raised.

How to eliminate wrong answers

Option B (TypeError) is wrong because `TypeError` occurs when an operation or function is applied to an object of inappropriate type (e.g., adding a string to an integer), not when a key is missing from a dictionary. Option C (ValueError) is wrong because `ValueError` is raised when a function receives an argument with the right type but an inappropriate value (e.g., `int('abc')`), not for missing dictionary keys. Option D (AttributeError) is wrong because `AttributeError` occurs when an invalid attribute reference or assignment is made (e.g., `None.some_method`), not when accessing a non-existent dictionary key.

184
MCQeasy

A developer writes a function `def log_event(message, level='INFO'):` that appends a formatted string to a list. The developer calls `log_event('disk full')` and then `log_event('retrying', level='WARN')`. What is the result of these two calls?

A.The first call uses 'INFO' for level and the second uses 'WARN', because the default applies only when the argument is omitted.
B.The first call raises a TypeError because a function with a default parameter must always receive that argument explicitly.
C.The second call raises a TypeError because positional and keyword arguments cannot be mixed in the same call.
D.Both calls use 'WARN', because the second call permanently changes the default for later invocations.
AnswerA

Default parameter values are used only when the caller does not supply that argument. The first call omits level, so the default 'INFO' is bound; the second call passes level explicitly by keyword, which overrides the default with 'WARN'. Both calls succeed and produce the intended log entries for the developer.

Why this answer

Default arguments make a parameter optional and are bound only when the caller omits that argument. An explicit keyword argument replaces the default for that single call without changing the function's definition, so the first invocation logs at INFO and the second at WARN. Calls that mix positional and keyword arguments are valid when each parameter is filled once.

Exam trap

The trap here is believing that passing a keyword argument in one call rewrites the function's default, when defaults are fixed at definition time and merely overridden per call.

185
MCQhard

According to PEP 8, which of the following is the recommended way to name a constant representing the maximum number of retries?

A.MAX_RETRIES
B.max_retries
C.1st_retry_limit
D.maxRetries
AnswerA

PEP 8 specifies that constants use all-uppercase letters with underscores separating words, so MAX_RETRIES matches the required naming convention for a maximum retries constant. Lowercase or camelCase forms are reserved for variables, functions and classes.

Why this answer

PEP 8 (Python Enhancement Proposal 8) recommends that constants be named using uppercase letters with underscores separating words, i.e., `MAX_RETRIES`. This convention distinguishes constants from regular variables, which use lowercase with underscores, and helps improve code readability and maintainability.

Exam trap

The PCEP exam often tests the distinction between variable naming conventions (snake_case for variables vs. UPPER_CASE for constants) and the rule that identifiers cannot start with a digit, leading candidates to confuse camelCase or invalid names with PEP 8 recommendations.

How to eliminate wrong answers

Option B is wrong because `max_retries` follows the PEP 8 naming convention for regular variables (snake_case), not constants, which should be in all uppercase. Option C is wrong because `1st_retry_limit` starts with a digit, which is invalid in Python (identifiers cannot begin with a number) and violates PEP 8 naming rules. Option D is wrong because `maxRetries` uses camelCase, which is not recommended by PEP 8 for Python code; PEP 8 specifies snake_case for variable names and UPPER_CASE for constants.

186
MCQeasy

A developer writes a script to calculate the average of three numbers: avg = (a + b + c) / 3. If a=5, b=10, c=15, what is the data type of avg?

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

Division with `/` in Python always yields a float, even when the operands are integers and divide evenly. Here (5 + 10 + 15) / 3 evaluates to 30 / 3, producing 10.0 rather than the integer 10, so avg is a float.

Why this answer

In Python, the division operator (/) always returns a float, even when dividing integers that result in a whole number. Here, (5 + 10 + 15) / 3 equals 30 / 3, which yields 10.0, a float. Therefore, the data type of avg is float.

Exam trap

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

How to eliminate wrong answers

Option B is wrong because bool is a data type for Boolean values (True/False), and the result of arithmetic division cannot be a bool. Option C is wrong because int would only be the type if integer division (//) were used, but the standard division operator (/) always produces a float in Python 3. Option D is wrong because str is a string data type, and the result of numeric division is never a string unless explicitly converted.

187
MCQmedium

A developer writes the following code to calculate a total price with tax: price = 19.99 tax_rate = 0.08 total = price + price * tax_rate print(round(total, 2)) What is printed?

A.1.6
B.21.59
C.21.5892
D.21.6
AnswerB

The expression price * tax_rate computes 19.99 * 0.08, which is approximately 1.5992. Adding that to the original price gives about 21.5892. The round function with two decimal places rounds this to 21.59, which is the value printed. This correctly applies multiplication before addition due to operator precedence.

Why this answer

Multiplication has higher precedence than addition, so price * tax_rate is evaluated first, producing the tax amount. That tax is then added to the base price, and the round function limits the result to two decimal places. The combined total is approximately 21.5892 before rounding, which becomes 21.59 when rounded to two decimal places.

Exam trap

The trap here is forgetting operator precedence and adding price and tax_rate before multiplying, which would produce a very different and incorrect total.

188
MCQeasy

A developer is writing a Python script to validate a list of usernames. The script must examine each username in the list and print 'Invalid' as soon as a username shorter than 3 characters is found, then stop checking the remaining usernames. Which control flow statement should be used inside the loop to terminate it immediately when the invalid username is encountered?

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

The break statement immediately terminates the innermost loop, so once a short username is found, the loop exits and no further usernames are checked. This matches the requirement to stop checking as soon as an invalid entry is detected, making it the correct control flow statement for early termination inside the loop.

Why this answer

The break statement exits the innermost loop immediately, which is exactly what is needed to stop checking usernames once an invalid one is found. The other statements either skip only one iteration, do nothing, or exit the whole function, so they do not satisfy the requirement to terminate the loop early while continuing the rest of the script.

Exam trap

The trap here is confusing continue with break, leading to skipping only the current item instead of stopping the entire loop.

189
MCQmedium

A program needs to check if a number is both positive and even. Which expression correctly implements this?

A.if num > 0 or num % 2 == 0:
B.if num > 0 and num % 2 == 0:
C.if num > 0 & num % 2 == 0:
D.if num > 0 and % 2 == 0:
AnswerB

The `and` operator short-circuits, so `num % 2 == 0` is only evaluated when `num > 0` already holds, satisfying both required conditions in one expression. Using `or` would accept any positive number regardless of parity, while nested `if` statements would work but are not the single expression the stem requests.

Why this answer

It uses the logical `and` operator to combine two conditions: `num > 0` (checks if the number is positive) and `num % 2 == 0` (checks if the number is even). Both conditions must be true for the overall expression to be true, which correctly implements the requirement of checking if a number is both positive and even.

Exam trap

Python Institute often tests the distinction between logical operators (`and`, `or`) and bitwise operators (`&`, `|`), as well as the correct syntax for the modulo operator, to catch candidates who confuse these concepts.

How to eliminate wrong answers

Option A is wrong because it uses the `or` operator, which returns true if either condition is true, meaning it would accept a positive odd number or a negative even number, not requiring both conditions. Option C is wrong because `&` is the bitwise AND operator, not a logical operator; it performs bitwise comparison on integers, which can produce unexpected boolean results and is not the correct way to combine conditions in an `if` statement. Option D is wrong because it has a syntax error: the modulo operator `%` is missing its left operand (it should be `num % 2 == 0`), making the expression invalid.

190
MCQeasy

What is the result of bool(0) in Python?

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

bool() converts any value to a Boolean using Python's truthiness rules. Zero is falsy, so bool(0) returns False. Non-zero numbers, non-empty strings and non-empty containers are truthy, but the integer 0 specifically evaluates to False.

Why this answer

The bool() function in Python converts any value to a Boolean. The integer 0 is considered a falsy value, so bool(0) returns False. This is because Python defines 0, None, empty collections, and False itself as falsy.

Exam trap

Python Institute often tests the misconception that bool(0) returns 0 or None, exploiting candidates who confuse the integer value 0 with the Boolean False, or who think that only the literal False keyword is falsy.

How to eliminate wrong answers

Option A is wrong because bool(0) does not return the integer 0; it returns a Boolean value, not an integer. Option B is wrong because bool(0) does not return None; None is a separate falsy value but is not the result of converting 0 to Boolean. Option C is wrong because 0 is not truthy; only non-zero integers evaluate to True when passed to bool().

191
MCQeasy

A Python script calculates the area of a circle: radius = 5; area = 3.14 * radius ** 2; print(area). What is printed?

A.78.5
B.157.0
C.25.0
D.31.4
AnswerA

The exponentiation operator ** binds tighter than multiplication, so radius ** 2 evaluates first, giving 25. Multiplying by 3.14 yields 78.5, which print outputs. This satisfies the stem's requirement to determine the exact value produced by the given expression.

Why this answer

78.5 because the expression `3.14 * radius ** 2` is evaluated according to Python's operator precedence: exponentiation (`**`) has higher precedence than multiplication (`*`), so `radius ** 2` computes 5 squared (25), then multiplied by 3.14 gives 78.5. The `print(area)` function outputs this value.

Exam trap

The Python Institute often tests operator precedence by embedding exponentiation in a multiplication expression, trapping candidates who mistakenly compute `(3.14 * radius) ** 2` (yielding 246.49) or who confuse area with circumference (2 * pi * r).

How to eliminate wrong answers

Option B (157.0) is wrong because it incorrectly assumes the formula uses diameter instead of radius (e.g., 3.14 * 10 ** 2 / 2 or 3.14 * 5 * 10). Option C (25.0) is wrong because it only computes `radius ** 2` and ignores multiplication by pi (3.14). Option D (31.4) is wrong because it incorrectly multiplies 3.14 by radius (5) instead of radius squared (25), effectively computing circumference (2 * pi * r) or a linear relationship.

192
MCQeasy

A QA engineer needs to run a test 5 times. Which loop construct is most appropriate?

A.do: ... while counter < 5
B.while counter < 5: ... counter += 1
C.for i in range(5): ...
D.def repeat(): ... repeat()
AnswerC

range(5) yields exactly five values, so the for loop body executes precisely five times without a manually managed counter. A while loop would need separate increment logic, making this construct the clearest fit for a fixed repetition count.

Why this answer

The `for i in range(5)` loop is the most idiomatic and concise way to repeat an action a fixed number of times (5 iterations) in Python. The `range(5)` generates a sequence from 0 to 4, and the loop body executes exactly 5 times, which directly matches the requirement to run a test 5 times without needing manual counter management.

Exam trap

The trap here is that candidates may confuse the `while` loop (option B) as equally valid, but the PCEP exam expects knowledge that `for` loops with `range` are the preferred and most Pythonic construct for fixed-count iteration, while `while` loops are intended for condition-based repetition where the number of iterations is not known in advance.

How to eliminate wrong answers

Option A is wrong because `do: ... while counter < 5` is not valid Python syntax; Python does not have a `do-while` loop construct (it uses `while` with a condition checked before each iteration). Option B is wrong because although it uses a valid `while` loop, it requires explicit initialization of `counter` before the loop and manual increment (`counter += 1`) inside the loop, making it less concise and more error-prone than the `for` loop for a fixed number of iterations. Option D is wrong because `def repeat(): ... repeat()` defines a recursive function that calls itself, which would cause infinite recursion (and a `RecursionError`) unless a base case is added; it is not a loop construct and is inappropriate for repeating a test exactly 5 times.

193
MCQhard

Which expression evaluates to False?

A.3 > 4
B.3 <= 3
C.3 == 3
D.3 != 2
AnswerA

The expression 3 > 4 evaluates to False because the greater-than operator compares the two integer operands and finds the left value smaller than the right. This directly satisfies the stem's requirement for an expression yielding False, unlike the other options whose comparisons return True.

Why this answer

The expression `3 > 4` evaluates to `False` in Python, as 3 is not greater than 4. All other options evaluate to `True` due to the correct application of comparison operators: `<=`, `==`, and `!=`.

Exam trap

Python Institute often tests whether candidates confuse the assignment operator `=` with the equality operator `==`, or mistakenly think that `<=` requires strict inequality, leading them to incorrectly evaluate `3 <= 3` as `False`.

How to eliminate wrong answers

Option B is wrong because `3 <= 3` evaluates to `True` — the `<=` operator returns `True` when the left operand is less than or equal to the right operand, and here they are equal. Option C is wrong because `3 == 3` evaluates to `True` — the `==` operator checks for value equality, and both integers are identical. Option D is wrong because `3 != 2` evaluates to `True` — the `!=` operator returns `True` when the operands are not equal, and 3 is indeed not equal to 2.

194
Multi-Selecthard

Which of the following statements about function arguments are true? (Select all that apply)

Select 4 answers
A.Keyword arguments can be passed in any order, regardless of their position in the function definition.
B.Using **kwargs allows passing a variable number of keyword arguments.
C.The *args parameter must always come after **kwargs in a function definition.
D.Using *args in a function definition allows passing a variable number of positional arguments.
E.Default arguments are evaluated once when the function is defined, not each time it is called.
AnswersA, B, D, E

Keyword arguments bind by parameter name rather than position, so the caller may supply them in any sequence and Python still maps each value to the matching parameter. This satisfies the stem's requirement that ordering is irrelevant, unlike positional arguments, which must follow the definition's sequence exactly.

Why this answer

The correct statements are A, B, D, and E. Keyword arguments can be passed in any order because they are matched by name (A). The **kwargs parameter collects additional keyword arguments into a dictionary (B).

The *args parameter collects additional positional arguments into a tuple (D). Default arguments are evaluated once at function definition time (E). Option C is incorrect because *args must always appear before **kwargs in a function definition.

Exam trap

A common pitfall in the PCEP exam is the order of *args and **kwargs: *args must precede **kwargs. Also, candidates often incorrectly think default arguments are evaluated each call, but they are evaluated once at definition time.

195
MCQhard

You are a developer on a team that maintains a legacy Python 2 codebase being migrated to Python 3. One function reads a file in text mode and counts word frequencies. In Python 2, the code used the dict.iteritems() method to iterate over the dictionary. After migration, the code raises AttributeError: 'dict' object has no attribute 'iteritems'. You need to update the code to work in Python 3 while minimizing changes. Which action should you take?

A.Replace iteritems() with viewitems().
B.Replace iteritems() with iteritems() from the six compatibility library.
C.Replace iteritems() with items().
D.Convert the dictionary to a list of tuples and iterate over the list.
AnswerC

Replacing `iteritems()` with `items()` restores iteration over the dictionary's key–value pairs, satisfying the Python 3 requirement that the legacy call be updated. Python 3 removed `iteritems()` entirely, and `items()` now returns a view object rather than a list, so the minimal edit resolves the `AttributeError` without restructuring the surrounding loop.

Why this answer

In Python 3, the `dict.iteritems()` method was removed because `dict.items()` now returns a view object that provides lazy iteration, similar to what `iteritems()` did in Python 2. Replacing `iteritems()` with `items()` is the minimal change that preserves the iteration behavior and works correctly in Python 3.

Exam trap

The PCEP exam often tests the misconception that Python 3 requires an external library or a different method name to achieve the same iteration behavior, when in fact `items()` alone is the correct and minimal replacement for `iteritems()`.

How to eliminate wrong answers

Option A is wrong because `viewitems()` does not exist in Python 3; it was a Python 2 method on dictionary views that is not available in Python 3. Option B is wrong because `iteritems()` from the `six` compatibility library would require adding an external dependency and is not a minimal change; the standard library already provides `items()` for the same purpose. Option D is wrong because converting the dictionary to a list of tuples is unnecessary and inefficient, as `items()` already provides the needed iteration without creating an intermediate list.

196
MCQmedium

A company needs to calculate the average of three test scores entered by a user. The scores are integers. The programmer writes the following code: s1 = input("Enter score 1: ") s2 = input("Enter score 2: ") s3 = input("Enter score 3: ") avg = (s1 + s2 + s3) / 3 print("Average:", avg) When run, the output is incorrect. What is the most likely cause?

A.The division by 3 will cause a ZeroDivisionError because 3 is not a float.
B.The division operator / always returns an integer, but the sum is not an integer.
C.The variable names s1, s2, s3 are not allowed because they start with a letter.
D.The input() function returns strings, so concatenation occurs instead of addition.
AnswerD

input() returns a string, so using + on strings concatenates them.

Why this answer

The `input()` function in Python always returns a string, even when the user types numbers. The `+` operator on strings performs concatenation (e.g., '5' + '3' + '2' becomes '532'), not numeric addition. Dividing the concatenated string by 3 then causes a `TypeError` (or produces an incorrect result if the string is implicitly converted), so the average calculation fails.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type, leading candidates to overlook the need for explicit type conversion before arithmetic operations.

How to eliminate wrong answers

Option A is wrong because dividing by an integer literal like 3 is perfectly valid; Python allows division by integers, and a `ZeroDivisionError` only occurs when dividing by zero, not by a non-zero integer. Option B is wrong because the `/` operator in Python 3 always returns a float, not an integer, and the issue is not about the return type of division. Option C is wrong because variable names starting with a letter (like s1, s2, s3) are perfectly allowed in Python; identifiers must start with a letter or underscore, so these names are valid.

197
MCQmedium

A programmer writes: result = 'Py' * 2 + 'thon'. What is the value of result?

A.'Py2thon'
B.'Python'
C.'Pyththon'
D.'PyPy'
AnswerB

Correct: 'Py'*2 = 'PyPy', plus 'thon' = 'Python'

Why this answer

In Python, the * operator on a string repeats it, and the + operator concatenates strings. 'Py' * 2 produces 'PyPy', then 'PyPy' + 'thon' results in 'Python'. This follows Python's operator precedence where * has higher precedence than +, so the multiplication is evaluated first.

Exam trap

The PCEP exam often tests the misconception that the * operator concatenates the string with the numeric value as a string (e.g., 'Py' * 2 becomes 'Py2'), or that it only repeats the last character, leading candidates to choose option A or C.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes that the * operator concatenates with a numeric representation, producing 'Py2thon', but Python's string repetition does not insert the number as a string. Option C is wrong because it suggests the repetition applies only to the last character, yielding 'Pyththon', but * repeats the entire string 'Py', not just the 'y'. Option D is wrong because it shows only the result of 'Py' * 2 as 'PyPy', ignoring the concatenation with 'thon'.

198
MCQmedium

Which of the following variable names is NOT valid in Python?

A.My_Var
B._myVar
C.2nd_place
D.myVar2
AnswerC

Python identifiers cannot begin with a digit, so `2nd_place` raises a `SyntaxError` at parse time, satisfying the stem's requirement for an invalid name. Letters, underscores and digits are permitted only after the first character, which must be a letter or underscore.

Why this answer

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

Exam trap

Python Institute often tests the rule that variable names cannot start with a digit, and the trap here is that candidates may focus on the underscore or mixed case and overlook the leading digit, mistakenly thinking '2nd_place' is acceptable because it contains letters and underscores.

How to eliminate wrong answers

Option A is wrong because 'My_Var' starts with a letter and contains only letters and underscores, which is perfectly valid in Python. Option B is wrong because '_myVar' starts with an underscore, which is allowed and commonly used for internal or private variables. Option D is wrong because 'myVar2' starts with a letter and contains letters and digits, which is valid as digits are allowed after the first character.

199
MCQmedium

A developer needs to check if a number is positive and even. Which conditional expression is correct?

A.if num > 0 & num % 2 == 0:
B.if num > 0 and num % 2 = 0:
C.if num > 0 && num % 2 == 0:
D.if num > 0 and num % 2 == 0:
AnswerD

Combining `num > 0` with `num % 2 == 0` using `and` requires both conditions to hold simultaneously, correctly identifying positive even numbers. The modulo operator returns zero only for even values, while the comparison excludes zero and negatives, satisfying the stem's dual constraint in one expression.

Why this answer

Python uses the keyword `and` for logical conjunction, and the equality operator is `==` (not `=`). The expression `num > 0 and num % 2 == 0` correctly checks that `num` is both greater than zero and divisible by 2 with no remainder, which defines a positive even number.

Exam trap

The PCEP exam often tests the distinction between logical operators (`and`, `or`) and bitwise operators (`&`, `|`), as well as the difference between assignment (`=`) and comparison (`==`), to catch candidates who confuse syntax from other programming languages.

How to eliminate wrong answers

Option A is wrong because `&` is the bitwise AND operator in Python, not the logical AND; it would perform a bitwise operation on the boolean results, which is not the intended logic. Option B is wrong because `=` is the assignment operator, not the equality comparison operator; using `num % 2 = 0` would cause a SyntaxError. Option C is wrong because `&&` is not a valid operator in Python; it is used in languages like C, Java, and JavaScript, but Python requires the keyword `and`.

200
MCQmedium

A developer runs the command and sees the output. Which statement about the data type is correct?

A.3.14 is a decimal.Decimal type.
B.3.14 is a float, but Python also treats it as a double.
C.3.14 is a float in Python.
D.3.14 is a string.
AnswerC

The literal 3.14 contains a decimal point, which makes Python create a float object rather than an int. Its type is therefore float, and this holds regardless of whether the value is displayed, stored in a variable, or passed to a function.

Why this answer

In Python, numeric literals with a decimal point, such as 3.14, are always interpreted as the built-in float type. Python does not have a separate 'double' type; its float is implemented as a C double (64-bit IEEE 754), but the language itself refers to it as float. This is a fundamental rule of Python's data type system.

Exam trap

The PCEP exam often tests the misconception that Python has separate 'float' and 'double' types, similar to languages like C or Java, when in fact Python's float is always double-precision and there is no distinct double type.

How to eliminate wrong answers

Option A is wrong because decimal.Decimal is a separate type from the decimal module, not a built-in literal type; 3.14 is not automatically a Decimal. Option B is wrong because Python does not have a distinct 'double' type — it uses a single float type, which is implemented as a double-precision floating-point number under the hood, but the language name is simply 'float'. Option D is wrong because 3.14 is not enclosed in quotes, so it is a numeric literal, not a string.

201
Multi-Selecteasy

Which TWO of the following are Python membership operators?

Select 2 answers
A.not
B.not in
C.in
D.is
E.and
AnswersB, C

'not in' is a membership operator that evaluates whether a value is absent from a sequence, returning a Boolean. It is the negated counterpart of 'in', satisfying the question's requirement for membership operators rather than identity or comparison operators.

Why this answer

Option B, 'not in', is a Python membership operator that evaluates to True when a specified value is absent from a sequence such as a list, tuple, string, or dictionary, making it correct. Option C, 'in', is likewise a membership operator that tests whether a value exists within a sequence, returning a Boolean result, so it is also correct. The other options are not membership operators: A 'not' is a logical (Boolean) operator, D 'is' is an identity operator that compares object identity, and E 'and' is a logical operator that combines Boolean expressions.

Exam trap

Python Institute often tests the distinction between membership operators ('in', 'not in') and identity operators ('is', 'is not'), as candidates frequently confuse 'is' with 'in' or mistake 'not' as a standalone membership operator when it must be paired with 'in'.

202
MCQeasy

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

A.my-var
B.2nd_place
C._count
D.class
AnswerC

A leading underscore is a legal identifier character in Python, and _count contains no spaces, digits at the start, or reserved keywords. It therefore satisfies Python's naming rules, unlike names beginning with a digit or using punctuation.

Why this answer

(_count) is correct because in Python, variable names can start with an underscore, and underscores are allowed anywhere in the name. The name _count follows all Python identifier rules: it starts with a letter or underscore, contains only letters, digits, or underscores, and is not a reserved keyword.

Exam trap

Python Institute often tests the rule that hyphens are not allowed in variable names, leading candidates to mistakenly think my-var is valid because it resembles common naming in other languages or file systems.

How to eliminate wrong answers

Option A is wrong because my-var contains a hyphen (-), which is not allowed in Python identifiers; only underscores are permitted as separators. Option B is wrong because 2nd_place starts with a digit, which violates Python's rule that identifiers must begin with a letter or underscore. Option D is wrong because class is a reserved keyword in Python and cannot be used as a variable name.

203
MCQhard

A dictionary: d = {1: 'a', 2: 'b', 3: 'c'}. Which code will cause a KeyError?

A.d.get(4)
B.if 4 in d: d[4]
C.d[4]
D.d.setdefault(4, 'd')
AnswerC

Accessing d[4] raises KeyError because the dictionary only maps keys 1, 2 and 3; no entry exists for key 4. Unlike get(), which returns None for absent keys, subscript access demands the key be present, so the missing key triggers the exception directly.

Why this answer

Accessing a dictionary key that does not exist using square bracket notation (d[4]) raises a KeyError. Since the dictionary d has keys 1, 2, and 3, the key 4 is absent, so d[4] triggers the error.

Exam trap

The PCEP exam often tests the distinction between safe dictionary access methods (get, setdefault, in) and the direct indexing operator ([]), expecting candidates to know that only [] raises a KeyError for missing keys.

How to eliminate wrong answers

Option A is wrong because d.get(4) returns None (or a default value if provided) instead of raising an error, as the get() method is designed to safely handle missing keys. Option B is wrong because the 'if 4 in d:' condition checks for the key's existence before accessing d[4], so the block is never executed when the key is absent, preventing a KeyError. Option D is wrong because d.setdefault(4, 'd') inserts the key 4 with value 'd' into the dictionary and returns 'd', avoiding any error.

204
MCQeasy

What is the correct way to read a floating-point number from user input and store it in a variable?

A.x = input(float())
B.x = input() as float
C.x = float(input())
D.x = input().float()
AnswerC

`float(input())` converts the entered string directly into a floating-point value, satisfying the requirement to read a number rather than text. `input()` always returns a string, so wrapping it in `float()` performs the necessary type conversion in one step, storing the numeric result in `x`.

Why this answer

`float(input())` first reads the user input as a string via `input()`, then converts that string to a floating-point number using the `float()` function. This is the standard and only valid way in Python to obtain a float from console input, as `input()` always returns a string.

Exam trap

The trap here is that candidates often confuse the order of operations, thinking they can apply a type conversion method directly on the input string (like `.float()`) or use non-existent syntax like `as float`, instead of wrapping the `input()` call with the `float()` function.

How to eliminate wrong answers

Option A is wrong because `input(float())` attempts to call `float()` with no argument (which returns 0.0) and then passes that float as the prompt argument to `input()`, not converting the user's input. Option B is wrong because `x = input() as float` is not valid Python syntax; the `as` keyword is used only in `with` statements and exception handling, not for type conversion. Option D is wrong because `x = input().float()` tries to call a method named `float()` on the string returned by `input()`, but strings have no such method, causing an AttributeError.

205
MCQmedium

A developer writes a function that modifies a global variable inside the function: count = 0 def increment(): count += 1 When called, an error occurs. What is the correct way to fix this?

A.Define count inside the function
B.Use the 'static' keyword
C.Pass count as an argument to the function
D.Use 'global count' inside the function
AnswerD

Assigning to count inside the function makes it a local variable, so the augmented assignment reads an unbound local and raises UnboundLocalError. Declaring 'global count' tells Python to bind the name to the module-level variable, allowing the increment to modify it.

Why this answer

The error occurs because Python treats 'count' as a local variable inside the function due to the assignment, but it is referenced before assignment. Using 'global count' inside the function explicitly tells Python to use the global variable, allowing modification. This is the correct fix for modifying a global variable from within a function.

Exam trap

PCEP often tests the misconception that Python has a 'static' keyword or that passing arguments can directly modify globals, when the correct answer is the 'global' declaration.

How to eliminate wrong answers

Option A is wrong because defining count inside the function would create a new local variable, not modify the global one, and would not resolve the intended behavior. Option B is wrong because Python does not have a 'static' keyword; that is from languages like C or Java. Option C is wrong because passing count as an argument would pass its value, but modifying it inside the function would still require returning and reassigning, which is not the direct fix for modifying the global variable.

206
MCQeasy

An application requires different messages based on temperature. Given: temp = 25 if temp > 30: print('Hot') elif temp > 20: print('Warm') else: print('Cool') What is the output?

A.No output
B.Hot
C.Cool
D.Warm
AnswerD

The first condition, temp > 30, evaluates false because 25 is not greater than 30. The elif condition, temp > 20, evaluates true, so its block runs and prints Warm; the else branch is skipped.

Why this answer

The condition `temp > 30` is False (25 is not greater than 30), so the first `if` block is skipped. The `elif temp > 20` condition is True (25 > 20), so the `print('Warm')` statement executes, outputting 'Warm'. Option D is correct.

Exam trap

The PCEP exam often tests the misconception that `elif` is optional or that the `else` block will execute even when a preceding `elif` is True, leading candidates to incorrectly choose 'Cool'.

How to eliminate wrong answers

Option A is wrong because the code will always produce output since the `else` clause ensures at least one branch executes, and here the `elif` condition is True. Option B is wrong because `temp` is 25, which is not greater than 30, so the `if` block for 'Hot' does not run. Option C is wrong because the `elif` condition `temp > 20` is True, so the `else` block (which prints 'Cool') is never reached.

207
MCQeasy

A developer needs to iterate over a list named `colors` and print each color on a separate line. Which code snippet correctly accomplishes this?

A.for (color in colors): print(color)
B.for color in colors: print(color)
C.for color in colors print(color)
D.for color in colors: print(color)
AnswerD

This is the correct syntax for a for loop in Python. The loop variable `color` takes each value from the list `colors` one at a time, and `print(color)` outputs it. This is the most straightforward and idiomatic way to iterate over a list and perform an action for each element.

Why this answer

The correct way to iterate over a list and print each element is to use a for loop with proper indentation and a colon at the end of the loop header. The loop variable takes each element from the list in turn, and the indented block executes for each element. This pattern is fundamental in Python for processing sequences.

Exam trap

The trap here is forgetting the colon at the end of the for statement or misindenting the loop body, which are common syntax errors for beginners.

208
Multi-Selecthard

Which THREE of the following are valid ways to create a list with elements 1, 2, 3? (Choose Three)

Select 3 answers
A.[1,2,3]
B.list(range(1,4))
C.(1,2,3)
D.[x for x in range(1,4)]
E.{1,2,3}
AnswersA, B, D

A list literal enclosed in square brackets with comma-separated values creates the list directly, producing exactly [1, 2, 3]. This is the most explicit list construction syntax and requires no iteration or conversion, satisfying the requirement for a list containing those three elements.

Why this answer

Option A, [1,2,3], is correct because a list literal enclosed in square brackets directly creates a list with the elements 1, 2, and 3 in order. Option B, list(range(1,4)), is correct because range(1,4) generates the integers 1, 2, 3 (the stop value 4 is exclusive), and wrapping it in the list() constructor materializes them as a list. Option D, [x for x in range(1,4)], is correct because this list comprehension iterates over range(1,4), producing the values 1, 2, 3 and collecting them into a new list.

Option C, (1,2,3), is not correct because parentheses create a tuple, not a list, and tuples are immutable and of a different type. Option E, {1,2,3}, is not correct because curly braces create a set, which is unordered and contains no duplicates, so it is not a list.

Exam trap

The PCEP exam often tests the distinction between list, tuple, and set literals, so candidates mistakenly choose curly-brace or parenthesis syntax as valid list creation methods.

209
MCQhard

A programmer needs to read a file line by line and process each line. Which of the following is the most memory-efficient and Pythonic approach?

A.with open('file.txt') as f: for line in f: print(line)
B.lines = open('file.txt').read().split('\n')
C.content = open('file.txt').read().splitlines()
D.for line in open('file.txt'): print(line)
AnswerA

Iterating directly over the file object yields one line at a time, so only a single line is held in memory. The with statement also guarantees the file is closed, satisfying the memory-efficiency and Pythonic requirements simultaneously.

Why this answer

It uses a `with` statement to ensure the file is properly closed after the block, and iterating directly over the file object reads one line at a time without loading the entire file into memory. This is both memory-efficient and Pythonic, as it leverages the file object's built-in iterator.

Exam trap

The PCEP exam often tests the distinction between using a `with` statement for guaranteed file closure versus relying on implicit garbage collection, and the misconception that reading the entire file at once is acceptable for small files, ignoring the principle of memory efficiency.

How to eliminate wrong answers

Option B is wrong because it reads the entire file into memory with `.read()`, then splits into a list, which is memory-inefficient for large files and does not close the file explicitly (relying on garbage collection). Option C is wrong because it also reads the entire file into memory with `.read()` and then splits into lines, wasting memory and leaving the file handle open. Option D is wrong because it does not use a `with` statement, so the file is not guaranteed to be closed promptly; it relies on the file object being garbage-collected, which is not Pythonic and can lead to resource leaks.

210
MCQhard

A developer is building a simple inventory check. The list stock holds integers representing item quantities. He wants to append the string 'low' to a separate list alerts once for each quantity that is less than 5. Which code correctly populates alerts?

A.for q in stock: if q < 5: alerts.append('low')
B.if any(q < 5 for q in stock): alerts.append('low')
C.alerts = ['low' for q in stock if q < 5] appended to the existing alerts list.
D.for q in stock: if q < 5: alerts.append('low') break
AnswerA

This loop visits every quantity in stock, tests whether it is below 5, and appends 'low' to alerts each time the test succeeds. Because the append is inside the if but inside the loop, the string is added once per qualifying quantity, and the number of entries in alerts matches the count of low quantities, which is exactly what the developer needs.

Why this answer

Appending inside a loop with a conditional adds one entry per qualifying quantity, which matches the requirement of one 'low' per item below 5. Breaking after the first match stops too early, using any collapses the count to a single Boolean decision, and rebinding alerts with a comprehension replaces rather than extends the existing list.

Exam trap

The trap here is placing break after the append, which looks like it just stops checking but actually prevents any later low quantities from being recorded.

211
Drag & Dropmedium

Order the steps to define and call a function in Python.

Drag or tap steps into the slots.

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

Why this order

Function definition starts with def, then the body, parameters are optional, and calling the function executes it.

212
MCQeasy

A developer writes a while loop to count down from 10 to 1 and then stop. Which condition should be used?

A.while counter != 0:
B.while counter >= 0:
C.while counter < 10:
D.while counter > 0:
AnswerD

With counter starting at 10 and decrementing, the loop must continue while counter remains above zero, so counter > 0 keeps iterations running for values 10 down to 1 and terminates once counter reaches 0, preventing an extra countdown iteration.

Why this answer

The while loop must continue as long as the counter is greater than 0, counting down from 10 to 1. When counter becomes 0, the condition `counter > 0` evaluates to False, and the loop terminates, stopping exactly at 1.

Exam trap

Python Institute often tests the off-by-one error where candidates choose `>= 0` thinking they need to include 0, but the requirement to stop at 1 means the loop must not execute when counter is 0.

How to eliminate wrong answers

Option A is wrong because `while counter != 0:` would cause the loop to continue until counter becomes 0, but if counter starts at 10 and decrements, it will reach 0 and stop correctly; however, this condition is less intuitive and could cause an infinite loop if counter skips 0 (e.g., decrement by 2). Option B is wrong because `while counter >= 0:` would include 0, causing the loop to run one extra iteration when counter is 0, printing 0 instead of stopping at 1. Option C is wrong because `while counter < 10:` would start as True (since 10 < 10 is False) and never execute the loop body, or if counter starts below 10, it would count up, not down.

213
MCQhard

A developer writes a function that retrieves a value from a dictionary and handles missing keys: def get_value(data, key): try: return data[key] except KeyError: return None What happens if data is not a dictionary but a list, and key is an integer index?

A.The function returns None because the except KeyError clause catches any error.
B.The function raises a KeyError because lists use integer indices, not keys.
C.The function raises a TypeError because lists do not support the [] operator.
D.The function returns the element at the specified index because lists support integer indexing.
AnswerD

Lists support integer indexing, so data[key] with an integer key retrieves the element at that position. The try block succeeds, and the function returns that element. The except KeyError clause is not triggered because no KeyError occurs. Thus, the function works correctly for lists with integer indices, returning the desired element.

Why this answer

The function uses a try-except block to handle KeyError, which is specific to dictionary key lookups. When data is a list and key is an integer, the expression data[key] performs list indexing, which succeeds if the index is valid. No KeyError is raised, so the except block is skipped, and the element is returned.

This shows that the same syntax can work for different types, but the exception handling is tailored to dictionaries.

Exam trap

The trap here is assuming that the except KeyError clause will catch any error or that list indexing raises KeyError.

214
MCQeasy

A game developer writes a loop to process a list of player scores: `scores = [45, 82, 67, 91]`. She wants to print only the scores that are greater than 80. Which loop correctly accomplishes this?

A.for score in scores: if score < 80: print(score)
B.for score in scores: if score >= 80: print(score)
C.for score in scores: if score > 80: print(score)
D.for score in scores: print(score) if score > 80: break
AnswerC

This loop iterates over each score, and the `if` statement filters those greater than 80. It will print 82 and 91. This is the straightforward way to apply a condition inside a loop and print matching elements.

Why this answer

To print only scores greater than 80, the loop must iterate over all scores and use an `if` statement with the `>` operator to print those that satisfy the condition. The correct snippet does exactly that, printing 82 and 91. Other options use incorrect comparison operators or misplaced print statements.

Exam trap

The trap here is mixing up the comparison operators `>` and `<`, or using `>=` which includes the boundary value when the requirement is strictly greater.

215
Multi-Selectmedium

Which TWO of the following expressions evaluate to True?

Select 2 answers
A.bool('')
B.bool([])
C.bool(1)
D.bool('False')
E.bool(0)
AnswersC, D

`bool(1)` returns True because Python's truth-value testing converts any non-zero integer to True, and only zero is falsy among integers. This satisfies the stem's requirement for an expression evaluating to True, since the integer literal 1 is non-zero.

Why this answer

Option C, bool(1), evaluates to True because any non-zero integer is truthy in Python, and 1 is the canonical non-zero value. Option D, bool('False'), also evaluates to True because any non-empty string is truthy regardless of its content — the string 'False' has five characters, so it is truthy. The unmarked options do not belong: bool('') is False because an empty string is falsy, bool([]) is False because an empty list is falsy, and bool(0) is False because zero is the integer falsy value.

Exam trap

The trap here is that candidates often mistakenly think the string `'False'` is falsy because it looks like the Boolean `False`, but Python evaluates truthiness based on the object's type and content, not its string representation.

216
MCQhard

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

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

Python's exponentiation operator `**` is right-associative, so `2 ** 3 ** 2` groups as `2 ** (3 ** 2)`, not `(2 ** 3) ** 2`. Evaluating the innermost exponent first gives `3 ** 2 = 9`, then `2 ** 9 = 512`. Left-associative evaluation would wrongly yield 64.

Why this answer

The expression `2 ** 3 ** 2` uses the exponentiation operator `**`, which in Python is right-associative. This means it is evaluated as `2 ** (3 ** 2)`, not `(2 ** 3) ** 2`. First, `3 ** 2` equals 9, then `2 ** 9` equals 512.

Therefore, option A is correct.

Exam trap

The trap here is that many candidates assume exponentiation is left-associative like most other arithmetic operators, leading them to compute `(2 ** 3) ** 2 = 64` instead of the correct right-associative `2 ** (3 ** 2) = 512`.

How to eliminate wrong answers

Option B (256) is wrong because it would result from `(2 ** 3) ** 2` (i.e., 8 ** 2 = 64) and then incorrectly doubling, not from the correct right-associative evaluation. Option C (64) is wrong because it represents the result of `(2 ** 3) ** 2` (8 squared), which is the left-associative misinterpretation of the expression. Option D (128) is wrong because it would come from `2 ** 7` (a miscalculation of the exponent), not from the correct `2 ** 9`.

217
MCQeasy

A developer is writing a Python script that must iterate over the characters of the string stored in variable `word` and print each character on its own line, without using index numbers. Which of the following loops accomplishes this?

A.while word: print(word)
B.for ch in word.split(): print(ch)
C.for ch in word: print(ch)
D.for ch in range(len(word)): print(ch)
AnswerC

This is correct because a Python `for` loop directly iterates over any iterable, and a string is an iterable that yields one character per iteration. Each pass binds `ch` to the next character and prints it, producing one character per line in order. No index counter or range is needed, which is the idiomatic and simplest solution for this scenario.

Why this answer

A Python `for` loop iterates directly over any iterable object, and strings are iterables that produce their characters one at a time. Binding each character to a loop variable and printing it yields exactly one character per line in the original order. The remaining constructs either iterate over numeric indexes, never advance the loop variable, or split the string into words rather than characters.

Exam trap

The trap here is assuming a `for` loop over a string needs `range()` and indexing, when the string itself is already directly iterable.

218
MCQmedium

A developer needs to count how many times each word appears in a list named words. The code starts with counts = {} and then iterates over the list. Which loop body correctly increments the count for each word, creating the key when it is first seen?

A.counts[word] += 1
B.counts.setdefault(word) + 1
C.counts[word] = counts.get(word, 0) + 1
D.counts.update(word, counts[word] + 1)
AnswerC

The get method returns the current count if the key exists and 0 otherwise, so the expression always produces a valid integer to increment. Assigning the result back to counts[word] creates the key on first encounter and updates it thereafter. This one-line idiom avoids a KeyError and correctly accumulates frequencies for every distinct word in the list.

Why this answer

Counting occurrences requires reading a possibly missing key without raising an exception and then storing the incremented value. The get method supplies a fallback of 0 for absent keys, and assigning the sum back to the dictionary both creates and updates the entry. The other forms either raise KeyError on first sight of a word or misuse a dictionary method.

Exam trap

The trap here is assuming that counts[word] += 1 initialises a missing key to zero automatically, when in fact it raises KeyError on the first occurrence.

219
MCQmedium

A program calculates BMI. User inputs weight and height as strings. Which line correctly converts to float?

A.weight = float(input)
B.weight = input().float()
C.weight = float(input())
D.weight = input(float())
AnswerC

float() parses a string such as "70.5" into a floating-point number, satisfying the stem's requirement to convert string input before arithmetic. Applying it directly to input() wraps the read value, so weight becomes numeric and BMI division works.

Why this answer

`float(input())` first reads the user's input as a string via `input()`, then converts that string to a floating-point number using the `float()` function. This is the standard Python pattern for converting user input to a numeric type.

Exam trap

Python Institute often tests the distinction between calling a function (`float(input())`) versus referencing it (`float(input)`) or chaining a non-existent method (`input().float()`), exploiting the common confusion that methods and functions are interchangeable.

How to eliminate wrong answers

Option A is wrong because `float(input)` passes the function object `input` itself, not the result of calling it, causing a TypeError. Option B is wrong because `input().float()` attempts to call a method named `float` on a string object, but strings have no such method; the correct approach is to use the built-in `float()` function. Option D is wrong because `input(float())` tries to call `input()` with a float argument (the result of `float()`), which is meaningless and will raise a TypeError since `input()` expects an optional string prompt, not a number.

220
MCQmedium

A developer writes a script that records a product price. The line is: price = 19.99 Later, the script runs print(type(price)). What is displayed?

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

Any numeric literal containing a decimal point in Python is a float, regardless of how many digits appear after it. Assigning 19.99 to price makes the variable reference a float object, and the built-in type function returns the class object for that type. Printing it displays the class name inside angle brackets, so the script outputs <class 'float'>.

Why this answer

Python infers a variable's type from the value assigned to it, and any numeric literal with a decimal point becomes a float. The type function returns the class of the object, and printing that class shows the type name in angle brackets. Since 19.99 includes a decimal point, the output is the float class.

Exam trap

The trap here is thinking a number with few decimal digits might be stored as an integer or a special decimal type rather than a plain float.

221
MCQhard

A function is supposed to modify a list passed as argument by appending an element. However, after calling the function, the original list remains unchanged. Which is the most likely cause?

A.The list is immutable.
B.The list is a tuple.
C.The function uses a local variable that shadows the global list.
D.The function reassigns the list parameter instead of mutating it.
AnswerD

Reassigning the parameter rebinds the local name to a new list object, so the caller's reference still points to the original, unmodified list. Appending mutates in place and would persist; assignment breaks that link, satisfying the stem's requirement that the original list stays unchanged.

Why this answer

In Python, when a list is passed to a function, the parameter refers to the same list object. If the function reassigns the parameter (e.g., `lst = [1, 2, 3]`), it only changes the local reference, not the original list. To modify the original list, the function must mutate it in-place using methods like `append()` or `extend()`, not reassign the parameter.

Exam trap

The PCEP exam often tests the distinction between mutating an object in-place versus reassigning the parameter name, exploiting the common misconception that reassigning a parameter inside a function will affect the original argument.

How to eliminate wrong answers

Option A is wrong because lists in Python are mutable objects; they can be modified in-place. Option B is wrong because a tuple is an immutable sequence, but the question explicitly states a list is passed, so this is a category error. Option C is wrong because while shadowing a global variable can cause confusion, the core issue here is that the function reassigns the parameter (a local variable) rather than mutating the list object itself; shadowing alone does not prevent mutation of the passed list.

222
MCQeasy

A student runs the following code in a Python 3.11 interactive session: >>> 7 // 2 What is displayed?

A.3.5
B.1
C.3
D.4
AnswerC

The double forward slash operator performs floor division, dividing the left operand by the right operand and rounding the result down to the nearest whole number. Since both 7 and 2 are integers, Python returns an integer, and 7 divided by 2 is 3 with a remainder, so the floor is 3.

Why this answer

Floor division with the double forward slash operator divides two numbers and rounds the result down to the nearest whole number. With integer operands, Python returns an integer. Because seven divided by two is three with a remainder of one, the floor value is three, and that integer is what the interactive session displays.

Exam trap

The trap here is confusing floor division with true division or with the modulo operator, since all three use similar symbols but produce different values.

223
MCQmedium

A team is developing a script that processes user input. They want to ensure that if the user enters a non-numeric value when asked for age, the program does not crash. Which approach should they use?

A.Use raw_input() and then int()
B.Use input() with a type check after input
C.Use int(input()) within a try-except block
D.Use a while loop to check if input.isdigit()
AnswerC

int() raises a ValueError when the input cannot be parsed as an integer, so wrapping the conversion in try-except lets the script catch that exception and handle it gracefully instead of terminating. This directly satisfies the requirement that non-numeric input must not crash the program.

Why this answer

Wrapping `int(input())` in a `try-except` block catches the `ValueError` that occurs when `int()` receives a non-numeric string. This prevents the program from crashing and allows graceful handling of invalid input, which is the standard Pythonic approach for robust user input validation.

Exam trap

The PCEP exam often tests the misconception that type checking after `input()` can prevent crashes, but candidates forget that `input()` always returns a string, making type checks like `isinstance()` useless without conversion, and that `isdigit()` is insufficient for numeric validation beyond simple positive integers.

How to eliminate wrong answers

Option A is wrong because `raw_input()` does not exist in Python 3 (it was renamed to `input()` in Python 2), and even if corrected, calling `int()` directly on non-numeric input will raise a `ValueError` and crash the program. Option B is wrong because using `input()` with a type check after input (e.g., `isinstance(value, int)`) is ineffective since `input()` always returns a string; the type check will never detect a non-numeric string as an integer, and the conversion to `int` would still crash if attempted. Option D is wrong because `input().isdigit()` only checks if the string consists entirely of digits, which fails for negative numbers, floats, or empty strings, and it does not handle the conversion or exception; the program would still crash if `int()` is called on a non-digit string.

224
Multi-Selectmedium

Which three of the following are Python arithmetic operators? (Choose three.)

Select 3 answers
A.+
B.|
C.-
D.&
E.*
AnswersA, C, E

Addition operator

Why this answer

The plus sign (+) is a standard Python arithmetic operator used for addition. It performs numeric addition when both operands are numbers, and also supports string concatenation, but its primary role in arithmetic contexts is addition.

Exam trap

Python Institute often tests the distinction between arithmetic operators and bitwise operators, trapping candidates who mistake the vertical bar or ampersand for arithmetic symbols due to their visual similarity to plus or multiplication signs.

Page 2

Page 3 of 7

Page 4

All pages