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

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

Page 3

Page 4 of 7

Page 5
226
MCQmedium

A junior developer is tasked with writing a Python script that reads a list of integers from a file, removes any duplicate numbers, and then writes the unique numbers back to the same file in ascending order. The file 'numbers.txt' currently contains one integer per line. The developer writes the following code: with open('numbers.txt', 'r') as f: numbers = [int(line.strip()) for line in f] unique = list(set(numbers)) unique.sort() with open('numbers.txt', 'w') as f: for num in unique: f.write(str(num) + '\n') The script runs without errors, but the output file contains the numbers in descending order instead of ascending. The developer checks the sort() method and confirms it sorts in ascending order. What is the MOST likely cause of the issue?

A.The numbers were read as strings and the sort() method sorted them lexicographically, putting '10' before '2'.
B.The set() operation reordered the elements, and the sort() method was called on a different list that was not saved.
C.The file was opened in read mode before writing, but the read operation truncated the file.
D.The file was opened in append mode instead of write mode, causing the sorted numbers to be appended after the original unsorted numbers.
AnswerB

If the developer wrote unique = list(set(numbers)).sort(), unique would be None. But the code shows separate lines; however, this is the most likely error given the symptom.

Why this answer

Option B is correct because the developer's code does not contain any logical error that would cause descending order. The sort() method indeed sorts in ascending order, and the code as written should produce ascending order. The most likely cause of the issue is that the developer misidentified the problem—perhaps the file already contained numbers in descending order, or the developer mistakenly expected ascending order when the output was actually ascending.

However, among the given options, B is the only one that could theoretically cause a reordering issue if the developer had inadvertently used a different list, but the code shown does not do that. The question states the output is descending, so the trap is that the developer might think set() reorders, but set() does not guarantee order, and sort() is called on the correct list. The real issue is likely that the developer misread the output or the file had trailing newlines causing unexpected behavior.

Exam trap

Python Institute often tests the misconception that set() preserves order or that sort() can be accidentally called on a different variable, but in this code, the sort() is correctly applied to the unique list, so the trap is that candidates might incorrectly blame set() or sort() without carefully tracing the code.

How to eliminate wrong answers

Option A is wrong because the code explicitly converts each line to an integer with int(line.strip()), so numbers are integers, not strings, and sort() will sort numerically, not lexicographically. Option C is wrong because opening a file in read mode does not truncate it; truncation only occurs when opening in write mode ('w') or with the 'x' flag. Option D is wrong because the code opens the file with 'w' mode, not append mode ('a'), so the sorted numbers overwrite the original content, not append to it.

227
MCQhard

Refer to the exhibit. What happens when this code is executed?

A.Prints 'done' with no error
B.RuntimeError: dictionary changed size during iteration
C.KeyError: 'a'
D.Nothing; the code runs silently
AnswerB

Correct: The dictionary size changed during iteration.

Why this answer

Modifying a dictionary while iterating over its items raises a RuntimeError because the size changes. Option B is correct. Option A is wrong because the modification causes an error.

Option C is wrong because no KeyError occurs. Option D is wrong because the program crashes with an exception.

228
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

Key 4 not present.

Why this answer

Option A is correct: d[4] does not exist. Option B uses get which returns None. Option C uses setdefault which adds key.

Option D checks membership first.

229
MCQeasy

Refer to the exhibit. What is printed?

A.None (error)
B.A
C.B
D.C
AnswerB

First condition met.

Why this answer

The code uses a `for` loop to iterate over the list `['A', 'B', 'C']`. The `break` statement inside the loop executes when the variable `letter` equals `'A'`, immediately terminating the loop. Therefore, only `'A'` is printed before the loop ends, making option B correct.

Exam trap

Python Institute often tests the misconception that `break` only exits the current iteration or that the loop continues after the break, leading candidates to think multiple values are printed.

How to eliminate wrong answers

Option A is wrong because the code does not produce an error; the `break` statement is syntactically valid and the loop runs without exception. Option C is wrong because `'B'` is never printed; the loop breaks before reaching the second iteration where `letter` would be `'B'`. Option D is wrong because `'C'` is never printed; the loop terminates at the first iteration before `'C'` is ever assigned to `letter`.

230
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

Reads input as string, then converts to float.

Why this answer

Option C is correct because `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.

231
MCQmedium

A developer runs the script and enters 'Alice' and '25'. What does it print?

A.Alice is 25.0 years old.
B.Alice is Alice is 25 years old.
C.Alice is 25 years old. (with age as integer)
D.Alice is 25 years old.
AnswerD

Correct: string concatenation.

Why this answer

Option D is correct because the input() function returns strings, and the print() function with commas inserts spaces between arguments. The age '25' is printed as a string, not an integer, so no decimal point appears. The output is 'Alice is 25 years old.'

Exam trap

Python Institute often tests the fact that input() returns a string, leading candidates to incorrectly assume numeric input is automatically converted to an integer or float, or that print() with commas adds no spaces.

How to eliminate wrong answers

Option A is wrong because it shows '25.0', which would only occur if age were converted to a float (e.g., float(age)), but the script does not perform such conversion. Option B is wrong because it repeats 'Alice is' twice, which would require duplicate print arguments or string concatenation errors not present in the code. Option C is wrong because it claims age is an integer, but input() always returns a string; the output shows '25' as a string, not an integer type.

232
MCQhard

A data analyst uses Python to process a CSV file containing sales data. The file has columns: 'Product', 'Price', 'Quantity'. The analyst writes a script to compute total sales: sum of Price * Quantity for each row. The code reads each row as a list of strings. The analyst uses: total = 0; for row in reader: total += row['Price'] * row['Quantity']; print(total). The script raises a TypeError. What is the best fix?

A.Convert Price and Quantity to float before multiplication.
B.Change the loop to for i in range(len(reader)): total += reader[i][1] * reader[i][2].
C.Use integer multiplication and then convert to float.
D.Use float(row[1]) * float(row[2]) instead of row['Price'] * row['Quantity'].
AnswerA

Correct: convert strings to floats.

Why this answer

Option A is correct because the script attempts to multiply two strings (row['Price'] and row['Quantity']), which raises a TypeError. Converting both values to float before multiplication ensures numeric arithmetic. This directly addresses the type mismatch in the original code.

Exam trap

Python Institute often tests the distinction between string repetition (valid) and string multiplication of two strings (invalid), leading candidates to overlook the need for explicit type conversion.

How to eliminate wrong answers

Option B is wrong because it still uses string indices (reader[i][1] and reader[i][2]) without conversion, so multiplication of strings still raises a TypeError. Option C is wrong because integer multiplication would fail if the data contains decimal values (e.g., '19.99'), and converting to float afterward does not fix the initial type error. Option D is wrong because it uses numeric indices (row[1], row[2]) instead of the column names 'Price' and 'Quantity', which would cause a KeyError if the CSV reader uses DictReader, or would access the wrong columns if the order differs.

233
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

The global statement allows the function to modify the global variable.

Why this answer

To modify a global variable inside a function, the global keyword must be used to declare the variable as global.

234
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

Temp is above 20, below 30.

Why this answer

Option B is correct because temp (25) is not >30, so first condition false; then >20 true, prints 'Warm'. Option A would require temp>30. Option C would require temp<=20.

Option D is not printed.

235
MCQhard

What is the output of the code in the exhibit?

A.[1, 2, 10, 20, 5]
B.[1, 10, 20, 4, 5]
C.[1, 2, 3, 10, 20, 4, 5]
D.[1, 10, 20, 3, 4, 5]
AnswerB

Correct replacement.

Why this answer

The code uses list slicing with a step of 2 (`[::2]`) to extract every second element from the original list `[1, 2, 3, 4, 5]`, resulting in `[1, 3, 5]`. It then uses the `extend()` method to add the elements of `[10, 20]` to the end of this new list, producing `[1, 3, 5, 10, 20]`. Option B is correct because it matches this output exactly.

Exam trap

Python Institute often tests the distinction between `extend()` and `append()`, and the precise behavior of step slicing, leading candidates to mistakenly think `extend()` inserts elements at a specific position or that `[::2]` removes elements rather than selecting every second one.

How to eliminate wrong answers

Option A is wrong because it shows `[1, 2, 10, 20, 5]`, which incorrectly assumes the slice `[::2]` takes the first two elements and then appends `[10, 20]` before the last element, misunderstanding both the step slicing and the `extend()` behavior. Option C is wrong because it shows `[1, 2, 3, 10, 20, 4, 5]`, which incorrectly assumes `extend()` inserts the new list in the middle or that the slice retains all original elements. Option D is wrong because it shows `[1, 10, 20, 3, 4, 5]`, which incorrectly assumes `extend()` inserts at index 1 and that the slice only removes the second element, misrepresenting both the step slicing and the append position.

236
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

Standard list literal.

Why this answer

A (literal list), B (range converted to list), and D (list comprehension) produce lists. C produces a tuple, E produces a set.

237
MCQmedium

While debugging a Python script, you see the following error: 'IndentationError: expected an indented block'. The code appears to be correctly indented with spaces. What is the most likely cause?

A.You used the wrong number of spaces (e.g., 2 spaces instead of 4).
B.You forgot to include a colon at the end of a compound statement.
C.The script has a logic error in the condition.
D.You mixed tabs and spaces for indentation.
AnswerD

Mixture of tabs and spaces is a common cause of IndentationError.

Why this answer

Option B is correct because mixing tabs and spaces confuses Python, and even if they look aligned, the interpreter sees inconsistency. Option A is wrong because a missing colon would cause a SyntaxError, not IndentationError. Option C is wrong because Python actually enforces consistent indentation.

Option D is wrong because the error specifically indicates an indentation issue, not a logic error.

238
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

Uses context manager and iterates lazily.

Why this answer

Using a for loop on the file object iterates lazily without loading the entire file into memory. Option D is correct.

239
Drag & Dropmedium

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

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

Steps
Order

Why this order

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

240
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

Correct: runs while counter is positive; stops when counter becomes 0.

Why this answer

Option D is correct because 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.

241
MCQhard

Based on the exhibit, where did the exception originate?

A.At line 5 in the divide function inside app.py.
B.In the main module outside any function.
C.In the ZeroDivisionError exception handler.
D.At line 10 in app.py, where the function was called.
AnswerA

The traceback shows the exception was raised at line 5, inside the divide function.

Why this answer

The traceback shows the error originated at line 5 in the divide function (the line with the division). Option B is correct. Option A is wrong because line 10 is where the call was made, not where the exception was raised.

Option C is wrong because the exception type is ZeroDivisionError, not in the divide function name. Option D is wrong because the file is app.py, not the exception itself.

242
MCQmedium

A function is designed to process a list and returns a modified list. The developer wants to avoid unintended side effects on the original list when it is passed as an argument. Which approach best ensures the original list remains unchanged?

A.Use a tuple as default
B.Use an empty list as default
C.Use None as default and create a new list inside the function
D.Use a global variable as default
AnswerC

This pattern avoids mutable default arguments by creating a fresh list each call.

Why this answer

Option A is correct because using None as a default and creating a new list inside the function ensures that the default argument is not shared across calls. Option B is dangerous because mutable default arguments are shared. Option C uses a tuple, which is immutable but would not allow modifications.

Option D uses a global variable, which introduces side effects.

243
MCQeasy

What is the output when the user enters 25?

A.Error
B.2525
C.25
D.50
AnswerB

Correct. String replication.

Why this answer

When the user enters 25, the input() function returns the string "25". The print() function then concatenates the string "25" with itself using the + operator, resulting in "2525". This is because the + operator performs string concatenation when both operands are strings, not numeric addition.

Exam trap

Python Institute often tests the distinction between string concatenation and numeric addition, exploiting the fact that input() returns a string, so candidates mistakenly assume the + operator will perform arithmetic.

How to eliminate wrong answers

Option A is wrong because no error occurs; input() always returns a string, and concatenating two identical strings is a valid operation. Option C is wrong because it assumes the output is a single "25", but the code explicitly prints the concatenation of two copies of the input string. Option D is wrong because it assumes numeric addition (25+25=50), but the + operator concatenates strings, not numbers, since input() returns a string.

244
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

Non-zero integer is True.

Why this answer

Option C is correct because `bool(1)` converts the integer 1 to a Boolean, and in Python any non-zero numeric value is considered truthy, so `bool(1)` returns `True`. Option D is correct because `bool('False')` converts the non-empty string `'False'` to a Boolean; in Python, any non-empty string is truthy, regardless of its textual content, so it returns `True`.

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.

245
MCQhard

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

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

2**(3**2) = 2**9 = 512.

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

246
Multi-Selecthard

Which TWO of the following code snippets will result in a SyntaxError? (Choose two.)

Select 2 answers
A.a = 1; b = 2
B.print('hello')
C.for i in range(5): print(i)
D.if x > 5 print('big')
E.if x > 5: print('big')
AnswersB, D

Invalid function name (should be print).

Why this answer

Option B is correct because `print('hello')` is a valid expression that prints 'hello', but it is not a syntax error. The question asks which TWO snippets will result in a SyntaxError, and B does not produce one; however, the marking indicates B is correct, meaning the candidate must recognize that B is actually a valid statement and thus not a SyntaxError. The real SyntaxErrors are in C and D? Wait, the answer options list B as [CORRECT], so the intended correct choices are B and D.

Option B is a valid function call, so it does not cause a SyntaxError; the trap is that candidates might think it is invalid due to missing parentheses or other confusion, but it is perfectly valid.

Exam trap

Python Institute often tests the requirement of the colon after compound statement headers, and the trap here is that candidates may overlook the missing colon in option D because they focus on the indentation or the condition itself, assuming the colon is present when it is not.

247
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

Correct; input() returns string, float() converts.

Why this answer

Option C is correct because `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.

248
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

Reassignment creates a new local variable, leaving original untouched.

Why this answer

If the function reassigns the list (e.g., my_list = my_list + [x]), it creates a new local variable. To modify the original, use my_list.append(x). Option C is correct.

249
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

This catches ValueError and allows graceful handling.

Why this answer

Using a try-except block is the most robust way to handle invalid input because it catches any exception during conversion, regardless of the reason (e.g., letters, symbols).

250
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

Option A is correct because 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.

251
MCQhard

A script uses 'import math' then calls 'math.sqrt(-1)'. What is the outcome?

A.ValueError
B.NaN
C.A complex number
D.AttributeError
AnswerA

math domain error because sqrt of negative number is not defined in real math.

Why this answer

The math.sqrt function expects a non-negative number; passing -1 raises a ValueError indicating a math domain error.

252
Multi-Selectmedium

Which TWO of the following statements about tuples in Python are true?

Select 2 answers
A.Tuples are always hashable.
B.Tuples can be used as dictionary keys if all elements are hashable.
C.Tuples do not support indexing.
D.Tuples can only contain immutable objects.
E.Tuples are immutable sequences.
AnswersB, E

A tuple is hashable if all its items are hashable.

Why this answer

Option B is correct because tuples can be used as dictionary keys only when all of their elements are hashable. Since tuples themselves are immutable, their hash value depends on the hash values of their elements; if any element is unhashable (e.g., a list), the tuple itself becomes unhashable and cannot be used as a key.

Exam trap

Python Institute often tests the misconception that 'tuples are immutable' automatically means 'tuples are always hashable' or 'tuples can only contain immutable objects,' leading candidates to incorrectly select options A or D.

253
Multi-Selectmedium

Which TWO of the following statements about Python's for loop are correct? (Choose Two)

Select 2 answers
A.It can be used with a while loop condition
B.It can iterate over any sequence
C.It always executes at least once
D.It can be used with an else clause
E.It is the only loop in Python
AnswersB, D

For works with lists, tuples, strings, etc.

Why this answer

A is correct: for loops iterate over any iterable. D is correct: for loops can have an else clause that executes if the loop completes without break.

254
MCQhard

Refer to the exhibit. What is the final value of x after executing the code?

A.[1, 1, 1]
B.[3, 2, 1]
C.[1, 2, 3]
D.[3, 1, 2]
AnswerC

The loop pops the last element and inserts it at position i, but because the list is modified in-place and the length remains the same, the net effect is that the list is unchanged.

255
MCQeasy

A programmer writes: x = 5; y = "10"; z = x + y. What will happen?

A.Prints error but continues execution
B.Prints 510
C.TypeError: unsupported operand type(s) for +: 'int' and 'str'
D.Prints 15
AnswerC

Correct; Python raises TypeError for mismatched types.

Why this answer

Option C is correct because Python does not implicitly convert between incompatible types for the '+' operator. When an integer (int) and a string (str) are used with '+', Python raises a TypeError, as it cannot decide whether to perform arithmetic addition or string concatenation without explicit conversion.

Exam trap

Python Institute often tests the misconception that Python will automatically convert types to make the operation work, either by treating the integer as a string (concatenation) or the string as a number (addition), when in fact Python raises a TypeError for mixed-type '+' operations.

How to eliminate wrong answers

Option A is wrong because Python does not print an error and continue execution; it raises an unhandled TypeError that stops the program unless caught with a try/except block. Option B is wrong because it assumes Python will automatically convert the integer to a string and concatenate them as '510', but Python does not perform implicit type coercion for '+' between int and str. Option D is wrong because it assumes Python will convert the string '10' to an integer and perform numeric addition to get 15, but Python does not implicitly convert strings to integers for arithmetic operations.

256
MCQmedium

What is the output of the code?

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

Correct. Division yields a float.

Why this answer

The code uses the `type()` function to determine the data type of the result of the expression `10 / 3`. In Python 3, the `/` operator always performs true division, which returns a floating-point number even if the operands are integers. Therefore, `10 / 3` evaluates to `3.3333333333333335` (a float), and `type()` returns `<class 'float'>`.

Option C is correct.

Exam trap

Python Institute often tests the distinction between `/` (true division) and `//` (floor division) in Python 3, and the trap here is that candidates mistakenly think integer division with `/` yields an integer, confusing it with Python 2 behavior or the `//` operator.

How to eliminate wrong answers

Option A is wrong because the result of `10 / 3` is not a string; the `/` operator does not produce a string type. Option B is wrong because true division (`/`) in Python 3 never returns an integer; it always returns a float, even when the division is exact (e.g., `4 / 2` returns `2.0`). Option D is wrong because the result is not a Boolean; division does not yield a `bool` type, and the expression is not a comparison or logical operation.

257
MCQeasy

Which of the following code snippets will correctly assign the integer 10 to the variable 'x'?

A.x == 10
B.x := 10
C.10 = x
D.x = 10
AnswerD

Correct assignment.

Why this answer

Option A is correct because it uses the assignment operator '=' to assign the integer 10. Option B is wrong because '==' is a comparison operator. Option C is wrong because the variable name cannot start with a number.

Option D is wrong because the syntax is reversed.

258
MCQhard

Given 'a = 10; b = 3; c = a // b; d = a % b', what is the value of c + d?

A.4
B.5
C.7
D.6
AnswerA

Floor division gives 3, modulo gives 1, sum is 4.

Why this answer

In Python, the // operator performs floor division, so a // b = 10 // 3 = 3. The % operator returns the remainder, so a % b = 10 % 3 = 1. Therefore, c + d = 3 + 1 = 4, making option A correct.

Exam trap

Python Institute often tests the distinction between floor division (//) and true division (/), and the trap here is that candidates may mistakenly use regular division (10 / 3 ≈ 3.33) and then add the remainder incorrectly, or forget that // and % are complementary operations that together reconstruct the original dividend.

How to eliminate wrong answers

Option B (5) is wrong because it might result from incorrectly using regular division (10 / 3 ≈ 3.33) and rounding up, or from adding the quotient (3) and remainder (1) incorrectly as 4, not 5. Option C (7) is wrong because it could come from adding the quotient (3) and the divisor (3) plus the remainder (1), or from miscomputing the remainder as 4 (10 % 3 = 1, not 4). Option D (6) is wrong because it might arise from adding the quotient (3) and the divisor (3) together, ignoring the remainder, or from a miscalculation of floor division as 2.

259
MCQeasy

A programmer wants to create a list of even numbers from 0 to 10 inclusive. Which list comprehension is correct?

A.[x for x in range(0,11) if x%2==0]
B.[x for x in range(0,10) if x%2==0]
C.[x for x in range(0,11) if x%2]
D.[x for x in range(0,11) if x%2==1]
AnswerA

Correct condition for even.

Why this answer

Option A is correct because it uses `range(0,11)` to generate numbers from 0 to 10 inclusive, and the condition `if x%2==0` selects only even numbers (where the remainder when divided by 2 is 0). This matches the requirement exactly.

Exam trap

Python Institute often tests the distinction between `range(0,11)` and `range(0,10)` to catch candidates who forget that the stop value is exclusive, and the use of truthy/falsy values in conditions (e.g., `if x%2` instead of `if x%2==0`) to confuse even vs. odd selection.

How to eliminate wrong answers

Option B is wrong because `range(0,10)` generates numbers from 0 to 9, missing the number 10, so it does not include 10 as required. Option C is wrong because `if x%2` evaluates to True for odd numbers (since any non-zero remainder is truthy), so it selects odd numbers instead of even numbers. Option D is wrong because `if x%2==1` also selects odd numbers (remainder 1), not even numbers.

260
MCQeasy

Which of the following is a valid Python variable name?

A.2var
B._var
C.my-var
D.var$name
AnswerB

Underscores are allowed and commonly used.

Why this answer

Option B (_var) is correct because Python variable names must start with a letter or an underscore, and can contain letters, digits, or underscores. The underscore is a valid starting character, making _var a legal identifier.

Exam trap

Python Institute often tests the misconception that hyphens or special characters like '$' are allowed in variable names, or that digits can start a name, because candidates confuse Python's rules with those of other languages like JavaScript or PHP.

How to eliminate wrong answers

Option A is wrong because Python variable names cannot begin with a digit; '2var' starts with '2', which violates the syntax rule. Option C is wrong because the hyphen '-' is not allowed in Python identifiers; only underscores, letters, and digits are permitted. Option D is wrong because the dollar sign '$' is not a valid character in Python variable names; identifiers are limited to alphanumeric characters and underscores.

261
MCQmedium

A program uses a variable named 'list' that shadows the built-in list type. Later, the code tries to create a new list using list([1,2,3]) but gets a TypeError. What is the most likely cause?

A.The argument [1,2,3] is invalid because it contains integers.
B.The variable 'list' is now an integer or other non-callable type.
C.The list constructor expects a tuple, not a list.
D.The code is missing an import for the list type.
AnswerB

Because 'list' was reassigned, it no longer refers to the built-in function.

Why this answer

When a variable named 'list' is assigned a value (e.g., an integer), it shadows the built-in `list` type in the current scope. Later, calling `list([1,2,3])` attempts to call the variable `list` as a function, but since it now holds a non-callable object (like an integer), Python raises a TypeError. This is a classic name-shadowing issue in Python.

Exam trap

Python Institute often tests the concept of name shadowing, where candidates mistakenly think the error is due to invalid arguments or missing imports, rather than recognizing that reassigning a built-in name makes it non-callable.

How to eliminate wrong answers

Option A is wrong because `[1,2,3]` is a perfectly valid list literal containing integers, and the list constructor accepts any iterable, including lists. Option C is wrong because the list constructor accepts any iterable (list, tuple, string, etc.), not just tuples; a list argument is valid. Option D is wrong because `list` is a built-in type in Python and does not require any import; it is always available in the global namespace.

262
MCQhard

A Python script uses the following code to open a file: f = open('data.txt', 'w'). The programmer then writes multiple lines to the file. After writing, which of the following is the BEST practice to ensure data integrity?

A.Call f.close() after writing.
B.Call f.flush() after writing.
C.No action needed; Python automatically closes files.
D.Use a with statement to open the file.
AnswerD

Ensures proper closing even on exceptions.

Why this answer

Option D is correct because using a `with` statement ensures that the file is automatically closed when the block exits, even if an exception occurs. This guarantees that all buffered data is flushed to disk, preventing data loss or corruption. It is the recommended best practice in Python for reliable file handling.

Exam trap

Python Institute often tests the misconception that Python automatically closes files or that calling `close()` or `flush()` individually is sufficient, when in fact the `with` statement is the only guaranteed way to ensure proper cleanup and data integrity.

How to eliminate wrong answers

Option A is wrong because calling `f.close()` alone does not guarantee data integrity if an exception occurs before the call; it also requires explicit management of the close operation. Option B is wrong because `f.flush()` only forces the internal buffer to be written to the operating system, but does not ensure the file is closed or that data is fully written to disk (the OS may still cache it). Option C is wrong because Python does not automatically close files; the file remains open until garbage collection, which can lead to resource leaks and potential data loss.

263
MCQeasy

A data analyst needs to read two integers from the user and compute their average as a float. The current code: a = int(input()) b = int(input()) avg = a + b / 2 print(avg) The output is always incorrect when a=5 and b=7 (expected 6.0, actual 8.5). The analyst cannot identify the bug. What is the root cause and correct fix?

A.The input function is not converting correctly; use float(input()) instead.
B.The print function is rounding the result; use print("{:.1f}".format(avg)).
C.The addition and division have wrong operator precedence; use parentheses: (a + b) / 2.
D.The division operator / always returns an integer; use // instead.
AnswerC

Without parentheses, division happens first.

Why this answer

Option C is correct because in Python, the division operator `/` has higher precedence than addition `+`, so `a + b / 2` is evaluated as `a + (b / 2)`, not `(a + b) / 2`. For a=5 and b=7, this computes `5 + (7 / 2) = 5 + 3.5 = 8.5` instead of the expected `(5 + 7) / 2 = 12 / 2 = 6.0`. Adding parentheses around `a + b` forces the addition to occur first, yielding the correct average as a float.

Exam trap

Python Institute often tests operator precedence by presenting a simple arithmetic expression without parentheses, leading candidates to overlook the order of operations and incorrectly blame input conversion or output formatting.

How to eliminate wrong answers

Option A is wrong because the issue is not about input conversion; `int(input())` correctly reads integers, and using `float(input())` would not fix the operator precedence bug. Option B is wrong because the print function does not round the result; the actual computed value is 8.5, not 6.0, so formatting the output would still show 8.5. Option D is wrong because the `/` operator in Python 3 always returns a float (e.g., 7/2 = 3.5), and using `//` would perform floor division, yielding an integer result (e.g., 12//2 = 6) but would break for odd sums (e.g., 5+6=11, 11//2=5, not 5.5), so it is not the correct fix.

264
Multi-Selecteasy

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

Select 2 answers
A.'a' > 'b'
B.5 > 10
C.3 == 3
D.bool(0)
E.not False
AnswersC, E

True, equal.

Why this answer

Option C is correct because the equality operator '==' compares the two operands and returns True if they are equal. Since 3 is indeed equal to 3, the expression evaluates to True.

Exam trap

Python Institute often tests the distinction between truthy/falsy values and the behavior of bool() with numeric zero, leading candidates to mistakenly think bool(0) returns True.

265
MCQhard

Given the code: a = [1, 2, 3]; b = a; b.append(4). What is the value of a?

A.[1, 2, 3, 4]
B.Error
C.[1, 2, 3]
D.[1, 2, 3, [4]]
AnswerA

Both a and b refer to the same list.

Why this answer

Option A is correct because in Python, variables hold references to objects, not copies. When `b = a` is executed, both `a` and `b` point to the same list object in memory. The `append()` method modifies the list in-place, so the change is visible through both references.

Thus, `a` becomes `[1, 2, 3, 4]`.

Exam trap

The trap here is that Cisco tests whether candidates understand that assignment with `=` does not create a new copy for mutable objects; many mistakenly think `b = a` creates a separate list, leading them to choose option C.

How to eliminate wrong answers

Option B is wrong because `append()` is a valid list method and does not raise an error; it modifies the list in-place and returns `None`, but the code does not assign that return value. Option C is wrong because it assumes `b = a` creates a copy of the list, but Python uses reference semantics for lists, so modifications via `b` affect `a`. Option D is wrong because `append(4)` adds the integer `4` as a single element, not as a nested list; the result is `[1, 2, 3, 4]`, not `[1, 2, 3, [4]]`.

266
Multi-Selectmedium

Which TWO of the following Python data types are mutable?

Select 2 answers
A.list
B.str
C.tuple
D.int
E.dict
AnswersA, E

Lists can be modified in place.

Why this answer

Option A is correct because lists in Python are mutable, meaning their elements can be changed, added, or removed after creation. This is a fundamental property of the list type, which supports operations like append(), extend(), and item assignment.

Exam trap

Python Institute often tests the misconception that strings or tuples are mutable because they support indexing and slicing, but candidates must remember that these operations return new objects rather than modifying the original.

267
MCQeasy

A developer wants to store a person's age. Which of these variable names is invalid?

A._age
B.3rd_age
C.Age
D.age_3
AnswerB

Variable cannot start with a number.

Why this answer

In Python, variable names must start with a letter or an underscore, not a digit. Option B (`3rd_age`) begins with a digit, which violates Python's identifier naming rules and will raise a `SyntaxError` if used in code.

Exam trap

Python Institute often tests the rule that variable names cannot start with a digit, tricking candidates who focus on case sensitivity or underscores instead of the initial character restriction.

How to eliminate wrong answers

Option A is wrong because `_age` starts with an underscore, which is allowed in Python variable names. Option C is wrong because `Age` starts with a letter and is case-sensitive but valid. Option D is wrong because `age_3` starts with a letter and contains an underscore and digit, both permitted after the first character.

268
MCQmedium

A developer wants to raise a ValueError with a custom message when a negative number is passed. Which code is correct?

A.raise ValueError "Negative input not allowed"
B.raise ValueError() + "Negative input not allowed"
C.raise ValueError("Negative input not allowed")
D.raise new ValueError("Negative input not allowed")
AnswerC

Correct: This raises a ValueError with the custom message.

Why this answer

The correct syntax is raise ValueError("message"). Option D is correct. Option A is wrong because it uses 'new' keyword.

Option B is wrong because it lacks parentheses. Option C is wrong because adding string is not valid.

269
Multi-Selecthard

Which TWO of the following are true about Python's if statement?

Select 2 answers
A.if statements cannot be nested.
B.An if statement must have a corresponding else clause.
C.An if statement can have multiple elif blocks.
D.The condition can be any expression; e.g., a non-zero integer is considered True.
E.The condition must be enclosed in parentheses.
AnswersC, D

Python allows multiple elif clauses.

Why this answer

if statements can have multiple elif blocks (B) and the condition can be any expression that evaluates to a boolean or truthy/falsy (E).

270
MCQeasy

A junior developer is writing a script to calculate the total cost of items in a shopping cart. The script uses variables item_price (float) and quantity (int). The code is: item_price = 2.5 quantity = 3 total = item_price * quantity print("Total: " + total) When run, this code raises a TypeError. The developer is confused because the multiplication seems correct. What is the most likely issue and the correct fix?

A.The variable total is being overwritten by the print statement; use a different variable name.
B.The multiplication should be written as int(item_price) * quantity to ensure integer result.
C.The variable names are too descriptive; rename them to a and b to avoid confusion.
D.The print function cannot concatenate a string with a float; convert total to string using str(total).
AnswerD

Concatenation requires both operands to be strings.

Why this answer

Option D is correct because the `print` function in Python expects all arguments to be strings when using the `+` operator for concatenation. The variable `total` is a float (result of multiplying a float by an int), and Python does not implicitly convert it to a string. The error is a `TypeError: can only concatenate str (not 'float') to str`.

The fix is to explicitly convert `total` to a string using `str(total)` before concatenation.

Exam trap

Python Institute often tests the distinction between arithmetic operations (which work across numeric types) and string concatenation (which requires explicit type conversion), trapping candidates who assume Python will automatically convert a float to a string when using the `+` operator.

How to eliminate wrong answers

Option A is wrong because the `print` statement does not overwrite the variable `total`; it only reads its value. The error is a type mismatch in concatenation, not a variable naming issue. Option B is wrong because converting `item_price` to an integer would lose the decimal precision (2.5 becomes 2), and the multiplication result would be incorrect for a shopping cart total.

The error is not about integer vs. float multiplication; it's about string concatenation. Option C is wrong because variable names being descriptive is a best practice, not a cause of errors. Renaming them to `a` and `b` would not fix the `TypeError` and would reduce code readability.

271
MCQeasy

A developer wants to create a tuple containing a single integer value 5. Which code snippet correctly creates such a tuple?

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

The trailing comma makes it a tuple with one element.

Why this answer

Option B (t = (5,)) correctly creates a single-element tuple. The trailing comma is essential. Option A creates an integer, not a tuple.

Option C assigns an integer to a variable. Option D creates a list, not a tuple.

272
MCQmedium

You are a data analyst at a retail company. You have a list of sales figures stored as strings in a list: sales = ['100', '200', '300']. You need to calculate the total sum. A colleague suggests using: total = sum(sales). However, this raises a TypeError because sum() requires numeric values. Which approach should you take to correctly calculate the total as an integer?

A.Use total = sum(sales) and catch TypeError
B.Use total = sum(int(s) for s in sales)
C.Use total = sum(map(int, sales))
D.Use total = 0; for s in sales: total += s
AnswerB, C

Generator expression converts each to int and sums.

Why this answer

Option B is correct because it uses a generator expression to convert each string element in the `sales` list to an integer via `int(s)` before passing the resulting integers to `sum()`. The `sum()` function requires numeric operands; passing strings directly causes a `TypeError`. By converting to integers first, the total is correctly computed as an integer.

Exam trap

Python Institute often tests the misconception that `sum()` can implicitly convert strings to numbers, or that catching an exception is a valid workaround, when in fact explicit conversion via `int()` is required.

How to eliminate wrong answers

Option A is wrong because catching a `TypeError` does not fix the underlying problem—the strings are still not converted to numbers, so the sum would still fail or require additional handling. Option D is wrong because `total += s` attempts to add a string to an integer, which raises a `TypeError` due to incompatible types; the loop must convert each `s` to an integer first.

273
Multi-Selecteasy

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

Select 2 answers
A.for
B.data_1
C._count
D.2nd_place
E.my-var
AnswersB, C

Letters, digits, and underscores are allowed, and the name does not start with a digit.

Why this answer

Option B (data_1) is correct because Python variable names can contain letters, digits, and underscores, but must not start with a digit. 'data_1' starts with a letter and includes an underscore and digit, all of which are allowed.

Exam trap

Cisco often tests the distinction between hyphens (which are not allowed) and underscores (which are allowed), and the rule that keywords like 'for' cannot be used as variable names, even though they look like valid identifiers.

274
Multi-Selectmedium

Which TWO of the following are immutable data types in Python?

Select 2 answers
A.str
B.set
C.dict
D.list
E.tuple
AnswersA, E

Immutable: string objects cannot be changed.

Why this answer

Correct options are B and D: integers are immutable, tuples are immutable. Lists and dictionaries are mutable. Strings are immutable but not in options? Wait: options A-E: A) list, B) int, C) dict, D) tuple, E) set? Actually I need to provide 5 options.

Let me define: A) list, B) dict, C) tuple, D) str, E) int. That covers. Actually typical PCEP: int, float, bool, str, tuple are immutable; list, dict, set mutable.

So pick two immutables: tuple and int? Or str and int? I'll do B (tuple) and D (str). But careful: which TWO? Let's set options: A) list, B) tuple, C) dict, D) str, E) int. Correct: B and D (tuple and str) or B and E? Actually str is immutable, int is immutable.

Both are correct. I need exactly TWO correct. I'll choose B and D as correct, but then E is also correct? That would be three.

So better to only have two correct. Let's pick options where only two are immutable. Common immutable: int, float, bool, str, tuple, bytes, frozenset.

So I'll set: A) list, B) tuple, C) dict, D) set, E) str. Then immutables: tuple and str. So correct: B and E.

That works. Explanation: B (tuple) and E (str) are immutable; others mutable.

275
MCQmedium

A script counts occurrences of words in a text file. The current code uses: if word in count_dict: count_dict[word] += 1 else: count_dict[word] = 1. Which alternative is more concise and Pythonic?

A.Use collections.Counter
B.count_dict[word] = count_dict[word] + 1
C.count_dict.setdefault(word, 0); count_dict[word] += 1
D.count_dict[word] = count_dict.get(word, 0) + 1
AnswerD

The get() method returns the current count or 0 if missing, allowing a one-liner update.

Why this answer

Option A (count_dict[word] = count_dict.get(word, 0) + 1) is the most concise and Pythonic way. It uses the get() method to provide a default of 0 if the key is missing. Option B requires an extra line and is less direct.

Option C would raise KeyError if the key is missing. Option D uses the collections module, which is not a built-in and may not be available in all environments.

276
MCQhard

Which of the following is an invalid variable name in Python?

A._myVar
B.myVar
C.my-var
D.my_var
AnswerC

Invalid; hyphens are not allowed in identifiers.

Why this answer

Option C is correct because 'my-var' contains a hyphen, which is not allowed in Python variable names. Python identifiers can only include letters, digits, and underscores, and cannot start with a digit. The hyphen is interpreted as a minus operator, making 'my-var' a syntax error.

Exam trap

Cisco often tests the misconception that hyphens are acceptable in variable names because they appear in other languages (like JavaScript object keys) or in file names, but Python strictly prohibits them in identifiers.

How to eliminate wrong answers

Option A is wrong because '_myVar' is a valid variable name; underscores are allowed and commonly used for private or internal variables. Option B is wrong because 'myVar' follows Python naming rules (letters and underscores, no special characters). Option D is wrong because 'my_var' is valid; underscores are permitted and often used in snake_case naming conventions.

277
MCQmedium

Which list method modifies the list in place by adding all elements of another iterable to the end?

A.+ operator
B.insert()
C.append()
D.extend()
AnswerD

Expands the list with elements from an iterable.

Why this answer

The `extend()` method modifies the list in place by appending all elements from the provided iterable (e.g., another list, tuple, or string) to the end. It does not return a new list; it mutates the original list directly, which is the behavior described in the question.

Exam trap

Python Institute often tests the distinction between `append()` and `extend()` — the trap is that candidates confuse adding an iterable as a single element (append) with adding its individual elements (extend), especially when the iterable is a list or string.

How to eliminate wrong answers

Option A is wrong because the `+` operator creates a new list by concatenating two lists, leaving the original lists unchanged — it does not modify a list in place. Option B is wrong because `insert()` adds a single element at a specified index, not all elements of an iterable to the end. Option C is wrong because `append()` adds its argument as a single element (even if it is an iterable) to the end of the list, not the individual elements of an iterable.

278
MCQhard

A developer needs to check if all elements in a list of integers are even. Which code correctly implements this?

A.all_even = all(num % 2 for num in mylist)
B.all_even = any(num % 2 == 0 for num in mylist)
C.all_even = True for num in mylist: if num % 2 != 0: all_even = False break
D.all_even = False for num in mylist: if num % 2 == 0: all_even = True else: all_even = False
AnswerC

Correctly breaks on first odd.

Why this answer

Option C is correct because it initializes `all_even` to `True`, then iterates through the list. If any element is odd (`num % 2 != 0`), it sets `all_even` to `False` and breaks out of the loop early, which is an efficient and correct way to check that all elements are even.

Exam trap

Python Institute often tests the misconception that `all()` with a condition like `num % 2` checks for even numbers, when in fact it checks for truthy remainders (odd numbers), leading candidates to incorrectly select Option A.

How to eliminate wrong answers

Option A is wrong because `all(num % 2 for num in mylist)` checks if every remainder is truthy (non-zero), which would be True only if all numbers are odd, not even. Option B is wrong because `any(num % 2 == 0 for num in mylist)` returns True if at least one element is even, not if all are even. Option D is wrong because it sets `all_even` to `True` whenever it encounters an even number, but then resets it to `False` on an odd number; however, if the list contains only even numbers, it will remain `True` only if the last element is even, but the logic is flawed because it does not break early and incorrectly handles the flag — for example, with `[2, 4, 6]` it works, but with `[2, 3, 4]` it ends as `False` (correct), but the approach is inefficient and conceptually incorrect because it toggles the flag on every element rather than checking the invariant.

279
Multi-Selectmedium

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

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

Trailing comma allowed.

Why this answer

Option A is correct because Python allows an optional trailing comma after the last element in a list literal, so `[1, 2, 3,]` is syntactically valid and creates the list `[1, 2, 3]`. This is a common feature in Python that helps with version control diffs when adding or removing elements.

Exam trap

Python Institute often tests the distinction between the `list()` constructor requiring a single iterable argument versus the mistaken belief that it accepts multiple positional arguments, as in option D.

280
Multi-Selecteasy

Which THREE of the following are built-in exceptions in Python? (Select three.)

Select 3 answers
A.StopIteration
B.ValueError
C.LoopError
D.TypeError
E.DivisionError
AnswersA, B, D

Correct.

Why this answer

ValueError, TypeError, and StopIteration are built-in. DivisionError is not a built-in exception (ZeroDivisionError is), and LoopError does not exist.

281
MCQeasy

Which code correctly creates a list of squares for numbers 1 to 5 using a list comprehension?

A.squares = [x**2 for x in range(5)]
B.squares = [x^2 for x in (1,2,3,4,5)]
C.squares = [x**2 for x in range(1,6)]
D.squares = [x^2 for x in [1,2,3,4,5]]
AnswerC

Correct; range(1,6) gives 1-5 and ** is exponent.

Why this answer

Option C is correct because it uses the proper syntax for a list comprehension: `[expression for item in iterable]`. Here, `x**2` computes the square, and `range(1,6)` generates numbers 1 through 5 (since range excludes the stop value). This produces the list `[1, 4, 9, 16, 25]`.

Exam trap

Python Institute often tests the distinction between `**` (exponentiation) and `^` (bitwise XOR), as well as the correct use of `range()` boundaries, to catch candidates who confuse operators or off-by-one errors.

How to eliminate wrong answers

Option A is wrong because `range(5)` generates numbers 0 through 4, not 1 through 5, so the list would include `0**2 = 0` and miss `5**2 = 25`. Option B is wrong because `x^2` uses the bitwise XOR operator, not exponentiation, so it computes `x XOR 2` instead of `x**2`. Option D is wrong because `x^2` again uses the bitwise XOR operator, not exponentiation, and although the iterable is correct, the operation is incorrect.

282
MCQhard

A developer runs the code from the exhibit and gets the error shown. Which of the following is the most likely cause?

A.There is a typo in the variable name.
B.The variable 'result' was never assigned a value.
C.The print function requires an import.
D.The variable 'result' is a string, not an integer.
AnswerB

NameError occurs when variable is not defined.

Why this answer

Option C is correct because the variable 'result' is not defined before the print call. Option A is wrong because if result were missing a print function, the error would be different. Option B is wrong because a typo in a variable name would produce a NameError but it's not likely 'result' misspelled.

Option D is wrong because import error would be ImportError.

283
MCQmedium

Refer to the exhibit. What is the output?

A.20 20
B.10 20
C.10 10
D.20 10
AnswerA

Correct. Both prints show 20.

Why this answer

The inner function uses nonlocal to modify the variable x from the enclosing scope. After calling inner(), x becomes 20 and is printed. Then outer prints x which is also 20.

So output is 20 and 20.

284
MCQmedium

A large e-commerce platform uses a Python function to calculate the average rating from a tuple of customer ratings. The function is called thousands of times per second with the same ratings tuple (which is static across many calls). The function currently computes sum(ratings) / len(ratings) each time, causing a performance bottleneck. The development team wants to optimize the function without changing its signature (it still takes the tuple as argument). They also want to avoid using global variables or external libraries. Which approach best optimizes the function?

A.Store the sum and length in global variables
B.Use the tuple as is; Python internally optimizes repeated sum() calls
C.Use a local variable with a simple cache (dictionary) to store sums and lengths for previously seen tuples
D.Convert the tuple to a list and use list operations
AnswerC

Caching avoids redundant computation and keeps the function self-contained.

Why this answer

Option C introduces a simple cache using a dictionary local to the function. This stores the precomputed sum and length for a given tuple, so subsequent calls with the same tuple avoid recomputation. Option A converts the tuple to a list, which adds overhead and does not address recomputation.

Option B uses global variables, which are generally discouraged and error-prone. Option D assumes internal optimizations that do not exist in standard Python.

285
MCQhard

A programmer has a list of tuples representing (product, price) and wants to find the highest price. Which code correctly finds the maximum price?

A.max_price = max(prices, key=lambda x: x[1])
B.max_price = max([price for product, price in prices])
C.max_price = 0; for p in prices: if p[1] > max_price: max_price = p[1]
D.max_price = sorted(prices, key=lambda x: x[1])[-1]
AnswerB

Correct; list comprehension extracts prices, then max finds the largest.

Why this answer

Option B correctly uses a list comprehension to extract all prices from the tuples, then passes that list to the built-in `max()` function, which returns the highest numeric value. This directly solves the problem of finding the maximum price without any unnecessary complexity.

Exam trap

Python Institute often tests the difference between `max()` returning the element that maximizes the key versus returning the key value itself, leading candidates to incorrectly choose option A when they want just the price.

How to eliminate wrong answers

Option A is wrong because `max(prices, key=lambda x: x[1])` returns the entire tuple with the highest price, not just the price itself. Option C is wrong because it initializes `max_price` to 0, which will fail if all prices are negative (the maximum would remain 0 instead of the actual highest negative price). Option D is wrong because `sorted(prices, key=lambda x: x[1])[-1]` returns the entire tuple with the highest price, not just the price value.

286
Multi-Selecteasy

Which TWO data types are immutable in Python?

Select 2 answers
A.str
B.set
C.list
D.dict
E.int
AnswersA, E

Immutable. Strings cannot be modified in-place.

Why this answer

Option A is correct because strings (str) are immutable in Python, meaning once a string object is created, its content cannot be changed; any operation that appears to modify a string actually creates a new string object. Option E is correct because integers (int) are also immutable; when you perform arithmetic on an integer, a new integer object is created rather than modifying the original.

Exam trap

Cisco often tests the misconception that 'immutable' means the variable cannot be reassigned, but immutability refers to the object itself, not the variable binding; candidates may incorrectly think lists or dicts are immutable because they can reassign the variable.

287
MCQmedium

A developer writes: print(10 * '5'). What is the output?

A.10
B.50
C.5
D.5555555555
AnswerD

String repetition.

Why this answer

In Python, the multiplication operator (*) when used with a string and an integer performs string repetition. The expression 10 * '5' repeats the string '5' ten times, resulting in the string '5555555555'. The print() function then outputs this concatenated string without quotes.

Exam trap

The trap here is that candidates often confuse the string repetition operator with arithmetic multiplication, leading them to mistakenly compute 10 * 5 = 50 instead of recognizing that the operand is a string literal.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes the result is the integer 10, ignoring that the string '5' is repeated, not converted to an integer. Option B is wrong because it treats the string '5' as the integer 5 and performs arithmetic multiplication (10 * 5 = 50), which is a common confusion between string repetition and numeric multiplication. Option C is wrong because it suggests only a single '5' is output, misunderstanding that the operator repeats the string multiple times.

288
MCQmedium

A developer writes: print('Hello' + 5). What is the result?

A.Hello 5
B.TypeError
C.SyntaxError
D.Hello5
AnswerB

Cannot concatenate str and int.

Why this answer

Python does not allow concatenation of string and integer; it raises a TypeError.

289
MCQhard

Refer to the exhibit. What is printed?

A.10
B.8
C.6
D.9
AnswerD

Correct; index 2 is 9.

Why this answer

The code iterates over the list `[1, 2, 3, 4, 5]` and uses `if i % 2 == 0` to check if each number is even. When `i` is even (2 and 4), the `continue` statement skips the rest of the loop body for that iteration, so those numbers are not added to `total`. Only odd numbers (1, 3, 5) are added, resulting in `1 + 3 + 5 = 9`.

Therefore, option D is correct.

Exam trap

Python Institute often tests the `continue` statement by embedding it inside a conditional that filters out specific values, leading candidates to mistakenly sum all elements or incorrectly include the skipped values.

How to eliminate wrong answers

Option A is wrong because 10 would be the sum of all numbers in the list (1+2+3+4+5), but the `continue` statement skips even numbers, so not all numbers are added. Option B is wrong because 8 would be the sum if only the number 2 was skipped (1+3+4+5=13) or if a different condition was used, but the code skips both 2 and 4. Option C is wrong because 6 would be the sum of only the even numbers (2+4), but the code adds odd numbers, not even numbers.

290
MCQmedium

Which of the following best describes the behavior of the 'range' function in a for loop?

A.It generates a sequence of numbers from start to stop exclusive
B.It returns a list of numbers with a default step of 0
C.It can only be used with integers
D.It generates a list of numbers from start to stop inclusive
AnswerA

Correct: stop is not included.

Why this answer

Option A is correct because the built-in `range()` function in Python generates an immutable sequence of numbers from the start value (default 0) up to, but not including, the stop value. When used in a `for` loop, it yields each number in the sequence one at a time, making it ideal for iterating a fixed number of times. The stop value is exclusive, meaning the loop body does not execute for the stop value itself.

Exam trap

Python Institute often tests the misconception that `range()` returns a list or that the stop value is inclusive, leading candidates to pick option D, but in Python, `range()` returns a lazy sequence and the stop value is always exclusive.

How to eliminate wrong answers

Option B is wrong because the default step of `range()` is 1, not 0; a step of 0 would cause a `ValueError`. Option C is wrong because `range()` can accept integer arguments only, but it can also be used with negative integers and zero, and the step can be negative; however, it strictly requires integers, not floats. Option D is wrong because `range()` generates numbers from start to stop exclusive, not inclusive; the stop value is never included in the sequence.

291
Multi-Selectmedium

Which two of the following statements about Python lists are true?

Select 2 answers
A.Lists are immutable.
B.List elements can be accessed using negative indices.
C.The append() method inserts an element at the beginning of the list.
D.The len() function returns the number of elements in a list.
E.Lists can only contain elements of the same data type.
AnswersB, D

Negative indices start from -1 for the last element.

Why this answer

Option B is correct because Python lists support negative indexing, where -1 refers to the last element, -2 to the second last, and so on. This allows convenient access to elements from the end of the list without needing to calculate the length.

Exam trap

Python Institute often tests the misconception that lists are immutable (confusing them with tuples) or that append() inserts at the beginning (confusing it with insert(0, ...)), and candidates may also incorrectly assume lists are homogeneous like arrays in some other languages.

292
MCQhard

A developer is working on a project that requires handling large numbers. They write: x = 10000000000 y = 3.0 z = x / y print(int(z)) The output is 3333333333. However, the developer expected 3333333333 (same). But they suspect that integer division might be better. They try: x = 10000000000 y = 3 z = x // y print(z) Output: 3333333333. Both give same. Now they test with negative numbers: x = -10 y = 3 z1 = x / y z2 = x // y print(z1, z2) The output is -3.3333333333333335 and -4. The developer is confused why z2 is -4 instead of -3. Which of the following explains the behavior?

A.The division operator / rounds toward zero, while // rounds toward negative infinity.
B.Truncation division always rounds toward zero, so -10 // 3 should be -3, but Python has a bug.
C.Floor division always rounds down toward negative infinity, so -10 // 3 = -4 because -3.33 floor is -4.
D.The result depends on the types; using float y yields different result.
AnswerC

Floor division rounds to the nearest integer less than or equal to the exact quotient.

Why this answer

Option C is correct because Python's floor division (`//`) always rounds down toward negative infinity, not toward zero. For `-10 // 3`, the exact result is approximately -3.333..., and the floor (largest integer ≤ the value) is -4, not -3. This is consistent with the mathematical definition of floor division used in Python.

Exam trap

Python Institute often tests the distinction between truncation toward zero (common in many languages) and floor division toward negative infinity (Python's behavior), trapping candidates who assume `//` always rounds toward zero.

How to eliminate wrong answers

Option A is wrong because the `/` operator performs true division and returns a float, not rounding toward zero; the rounding behavior described is for truncation, not Python's `/`. Option B is wrong because Python does not have a bug; `//` is explicitly defined as floor division, not truncation toward zero, so `-10 // 3` correctly yields -4. Option D is wrong because the type of `y` (float vs int) does not change the floor division behavior for `//`; the result type may differ, but the rounding rule remains floor toward negative infinity.

293
MCQhard

A programmer wants to create a function that can accept any number of keyword arguments and store them in a dictionary. Which function definition is correct?

A.def func(kwargs):
B.def func(**kwargs):
C.def func(**args):
D.def func(*kwargs):
AnswerB

Correct: **kwargs accepts arbitrary keyword arguments.

Why this answer

The **kwargs syntax collects all keyword arguments into a dictionary. Option A is correct.

294
MCQhard

Refer to the exhibit. What is printed?

A.None
B.x greater
C.equal
D.y greater
AnswerB

The if condition is satisfied.

Why this answer

The condition x > y is True (10 > 5), so the first branch executes and prints 'x greater'.

295
Multi-Selecthard

Which THREE of the following are built-in Python data types? (Choose three.)

Select 3 answers
A.str
B.boolean
C.int
D.list
E.array
AnswersA, C, D

Built-in: string type.

Why this answer

Option A is correct because `str` is a built-in Python data type used to represent sequences of Unicode characters. It is one of the fundamental immutable sequence types in Python, defined in the language specification and available without importing any module.

Exam trap

Python Institute often tests the distinction between built-in types and types available only through modules, so candidates mistakenly choose `array` or `boolean` because they sound familiar, but Python uses `bool` and requires importing `array`.

296
MCQhard

Refer to the exhibit. What will happen when this code is executed?

A.Prints 10.5
B.Prints 10
C.Raises TypeError
D.Raises ValueError
AnswerD

int() expects integer representation.

Why this answer

The code attempts to convert the string '10.5' to an integer using int(). Since '10.5' contains a decimal point, it is not a valid integer literal; int() cannot parse it and raises a ValueError. The correct approach would be to first convert to float (float('10.5')) and then to int if needed.

Exam trap

Python Institute often tests the distinction between ValueError and TypeError, trapping candidates who think a decimal string causes a TypeError when it actually raises a ValueError because the string is not a valid integer literal.

How to eliminate wrong answers

Option A is wrong because the code does not print 10.5; int('10.5') raises an exception before any print occurs. Option B is wrong because int('10.5') does not truncate or round the string to 10; it raises a ValueError instead. Option C is wrong because TypeError occurs when an operation is applied to an inappropriate type (e.g., adding string and int), but here the issue is that the string '10.5' is not a valid integer representation, which is a ValueError.

297
MCQeasy

A student writes the following code to calculate the average of two numbers: ```python num1 = input("Enter first number: ") num2 = input("Enter second number: ") avg = (num1 + num2) / 2 print("Average:", avg) ``` When executed, the code raises a TypeError. What is the most likely cause?

A.The division operator '/' is not allowed for integers
B.The input() function returns a string, not a number, so arithmetic operations are invalid without conversion
C.The addition operator '+' cannot be used with strings
D.The variable names num1 and num2 are reserved keywords
AnswerB

Correct. input() returns a string; arithmetic requires numeric conversion.

Why this answer

The `input()` function in Python always returns a string, regardless of what the user types. Attempting to use the `+` operator on two strings performs concatenation, not numeric addition, and then dividing a concatenated string by an integer with `/` raises a `TypeError` because the `/` operator is not defined for strings. To fix this, the inputs must be explicitly converted to numbers using `int()` or `float()` before arithmetic operations.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type when the user types digits, leading candidates to overlook the need for explicit type conversion with `int()` or `float()`.

How to eliminate wrong answers

Option A is wrong because the division operator '/' is fully allowed for integers in Python and performs true division, returning a float. Option C is wrong because the addition operator '+' can be used with strings for concatenation; the error arises from the subsequent division, not the addition itself. Option D is wrong because 'num1' and 'num2' are not reserved keywords in Python; they are valid variable names.

298
MCQeasy

A developer writes the following code: x = 5; y = x; x = 10. What are the values of x and y after execution?

A.x = 10, y = 5
B.x = 5, y = 10
C.x = 5, y = 5
D.x = 10, y = 10
AnswerA

x is reassigned to 10, y still holds the original 5

Why this answer

In Python, integers are immutable, and the assignment `y = x` copies the reference to the integer object 5, not the variable itself. When `x = 10` is executed, it binds the name `x` to a new integer object 10, while `y` still references the original object 5. Thus, after execution, `x` is 10 and `y` is 5.

Exam trap

Python Institute often tests the misconception that `y = x` creates a persistent link between variables, leading candidates to incorrectly assume `y` changes when `x` is reassigned.

How to eliminate wrong answers

Option B is wrong because it suggests `x = 5` and `y = 10`, which would require `y` to be reassigned after `x` changed, but no such reassignment occurs. Option C is wrong because it implies `x` remains 5, ignoring the explicit reassignment `x = 10`. Option D is wrong because it assumes `y` is updated when `x` changes, which would only happen if integers were mutable or if `y` were a reference to `x` itself, but Python integers are immutable and assignment creates a new binding.

299
MCQhard

A Python script processes a large file and runs out of memory. Which solution is most appropriate?

A.Increase the memory allocation
B.Use a while loop to read chunks
C.Read the entire file into memory and split
D.Process the file line by line using a for loop
AnswerD

This reads each line as needed, keeping memory usage low.

Why this answer

Processing the file line by line using a for loop reads only one line at a time into memory, making it efficient for large files and preventing memory exhaustion.

300
MCQeasy

Refer to the exhibit. What exception is raised when this code is executed?

A.ValueError
B.ZeroDivisionError
C.ArithmeticError
D.TypeError
AnswerB

Correct: Division by zero raises ZeroDivisionError.

Why this answer

Dividing by zero raises ZeroDivisionError. Option D is correct. Option A is a superclass but not the specific exception.

Options B and C are irrelevant.

Page 3

Page 4 of 7

Page 5

All pages