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

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

Page 5

Page 6 of 7

Page 7
376
MCQmedium

What is the output of the code in the exhibit?

A.{5:'apple', 6:'banana', 6:'cherry'}
B.{'apple':5, 'banana':7, 'cherry':6}
C.{0:'apple', 1:'banana', 2:'cherry'}
D.{'apple':5, 'banana':6, 'cherry':6}
AnswerD

Correct mapping of items to their lengths.

Why this answer

The dictionary comprehension creates a dict with each item as key and its length as value. {'apple':5, 'banana':6, 'cherry':6}. Option C is correct. Option A has values wrong (7 for banana).

Option B swaps keys and values. Option D uses index numbers, not lengths.

377
MCQmedium

What is the output of print(10 // 3, 10 % 3)?

A.1 3
B.3.33 1
C.3 3
D.3 1
AnswerD

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

Why this answer

Option D is correct because the // operator performs floor division, which divides 10 by 3 and discards the fractional part, yielding 3. The % operator returns the remainder of that division, which is 1. The print function outputs both values separated by a space, resulting in '3 1'.

Exam trap

Python Institute often tests the distinction between floor division (//) and true division (/), and the trap here is that candidates mistakenly think // performs regular division or confuse the order of quotient and remainder in the output.

How to eliminate wrong answers

Option A is wrong because it reverses the results, showing the remainder first (1) and the quotient second (3), which misinterprets the order of operations in the print statement. Option B is wrong because it uses true division (/) instead of floor division (//), giving 3.33, and incorrectly pairs it with remainder 1. Option C is wrong because it shows the quotient as 3 but incorrectly gives the remainder as 3, likely confusing the remainder with the divisor or the quotient itself.

378
MCQeasy

A developer writes code to iterate over a list and break when a certain condition is met. Which keyword is used to exit the loop prematurely?

A.break
B.stop
C.exit
D.continue
AnswerA

Correct keyword to exit a loop.

Why this answer

The `break` keyword is used in Python to immediately exit the nearest enclosing loop (for or while) when a specified condition is met, allowing the program to resume execution at the next statement after the loop. This is the standard mechanism for premature loop termination in Python, as defined in the language specification.

Exam trap

Python Institute often tests the distinction between `break` and `continue`, where candidates mistakenly think `continue` can exit a loop, but it only skips the current iteration and proceeds to the next one.

How to eliminate wrong answers

Option B is wrong because `stop` is not a Python keyword; it has no meaning in loop control and would raise a NameError if used. Option C is wrong because `exit` is a function (typically from the `sys` module) used to terminate the entire program, not just the loop, and is not a keyword for loop control. Option D is wrong because `continue` does not exit the loop; it skips the rest of the current iteration and jumps to the next iteration of the loop.

379
MCQmedium

A developer writes a Python script that calculates the average of a list of numbers. The script sometimes produces a ZeroDivisionError. Which of the following is the MOST appropriate way to handle this error to keep the script running?

A.Check if len(numbers) == 0 before division and skip calculation if true.
B.Use an if statement to check if the list is empty and print a warning message.
C.Remove the last element from the list if it is empty.
D.Wrap the division in a try/except block and catch ZeroDivisionError, then set the average to 0.
AnswerD

Handles the error gracefully and allows continuation.

Why this answer

Option D is correct because it uses a try/except block to catch the ZeroDivisionError specifically, which is the most robust and Pythonic way to handle runtime errors. This approach keeps the script running by setting the average to 0 when the list is empty, without relying on pre-checks that might miss other causes of division by zero (e.g., if the sum is 0 but the list is not empty). In Python, exception handling is preferred for error-prone operations like division, as it separates normal logic from error handling cleanly.

Exam trap

Python Institute often tests the distinction between error prevention (e.g., if-checks) and error handling (e.g., try/except), where candidates mistakenly choose a pre-check that only partially addresses the error, while the correct answer uses exception handling to cover all cases.

How to eliminate wrong answers

Option A is wrong because checking len(numbers) == 0 before division only prevents the error for empty lists, but a ZeroDivisionError can also occur if the divisor is zero due to other reasons (e.g., a calculated denominator), making this approach incomplete. Option B is wrong because printing a warning message does not prevent the ZeroDivisionError from occurring; the script would still crash unless the division is skipped or handled. Option C is wrong because removing the last element from an empty list raises an IndexError, not a ZeroDivisionError, and it does not address the root cause of the division by zero.

380
MCQeasy

Which of the following is an immutable data type in Python?

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

Tuples are immutable.

Why this answer

A tuple is immutable because once created, its elements cannot be changed, added, or removed. This is enforced by Python's internal structure: tuples are stored as a fixed-length array of object references, and no methods exist to modify them in place.

Exam trap

Python Institute often tests the misconception that 'immutable' means the variable cannot be reassigned, when in fact it means the object's contents cannot be changed — a common trap that leads candidates to incorrectly label strings or tuples as mutable.

How to eliminate wrong answers

Option B is wrong because a set is mutable — you can add or remove elements using methods like add() and discard(). Option C is wrong because a list is mutable — you can modify, append, or delete elements via indexing, append(), or pop(). Option D is wrong because a dict is mutable — you can add, update, or delete key-value pairs using assignment or methods like pop() and update().

381
MCQeasy

Which of the following variable names is valid in Python?

A.1st_value
B._count
C.my-var
D.class
AnswerB

Valid: underscores are allowed at the start.

Why this answer

Option B (_count) is valid because Python allows identifiers to start with an underscore, and it contains only letters and underscores. Python variable names must start with a letter or underscore, followed by letters, digits, or underscores, and cannot be a reserved keyword.

Exam trap

Python Institute often tests the misconception that underscores are not allowed or that hyphens are acceptable in variable names, leading candidates to reject _count or accept my-var.

How to eliminate wrong answers

Option A is wrong because variable names cannot start with a digit; '1st_value' begins with '1', which violates Python's identifier rules. Option C is wrong because hyphens are not allowed in Python identifiers; 'my-var' uses a hyphen, which Python interprets as a subtraction operator. Option D is wrong because 'class' is a reserved keyword in Python used to define classes, so it cannot be used as a variable name.

382
MCQeasy

A developer writes: x = 5; y = 2.0; z = x / y; print(type(z)). What is the output?

A.<class 'str'>
B.<class 'int'>
C.TypeError
D.<class 'float'>
AnswerD

x / y returns a float because y is float.

Why this answer

In Python, the division operator (/) always returns a float, even when dividing two integers. Here, x is an integer (5) and y is a float (2.0), so the result is a float (2.5). The type() function returns <class 'float'>, making D correct.

Exam trap

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

How to eliminate wrong answers

Option A is wrong because the result of division is a number, not a string; type() would never return <class 'str'> for a numeric operation. Option B is wrong because Python 3's / operator always produces a float, even if the division is exact (e.g., 5/5 returns 1.0, not 1). Option C is wrong because there is no TypeError; Python allows division between int and float without issue, implicitly converting the int to a float for the operation.

383
MCQmedium

An accountant uses a Python script to calculate tax: tax = price * 0.08. For price=19.99, tax results in 1.5992. However, the output should be rounded to two decimal places. Which expression should replace the current one?

A.tax = round(price * 0.08)
B.tax = round(price * 0.08, 2)
C.tax = price * 0.08
D.tax = int(price * 0.08 * 100) / 100
AnswerB

Correctly rounds to two decimal places.

Why this answer

Option B is correct because the built-in `round()` function with a second argument of 2 rounds the floating-point result of `price * 0.08` to exactly two decimal places, which matches the requirement for currency formatting. The other options either omit rounding, round to an integer, or use integer truncation that can produce incorrect results for negative numbers or edge cases.

Exam trap

Python Institute often tests the distinction between `round(x)` (rounds to integer) and `round(x, n)` (rounds to n decimal places), and the trap here is that candidates may choose Option A thinking it rounds to two decimals, or Option D thinking integer truncation is equivalent to rounding.

How to eliminate wrong answers

Option A is wrong because `round(price * 0.08)` with no second argument rounds to the nearest integer (0 decimal places), producing 2 instead of 1.60. Option C is wrong because it simply computes the raw floating-point value 1.5992 without any rounding, leaving extra decimal places. Option D is wrong because `int(price * 0.08 * 100) / 100` truncates toward zero, which for positive values works here but fails for negative numbers (e.g., -19.99 would give -1.59 instead of -1.60) and does not perform proper rounding.

384
MCQhard

A developer is using a lambda function that takes two arguments and returns their sum. Which of the following lambda expressions is correct?

A.lambda a, b: a + b
B.lambda a, b: a + b
C.lambda a, b: return a + b
D.def add(a, b): return a + b
AnswerA

Correct lambda syntax with implicit return.

Why this answer

Option A is correct because a lambda function in Python is defined using the `lambda` keyword, followed by a comma-separated list of parameters, a colon, and a single expression that is implicitly returned. The expression `a + b` computes the sum of the two arguments without needing an explicit `return` statement, making it the proper syntax for a lambda that returns the sum.

Exam trap

Python Institute often tests the misconception that lambda requires an explicit `return` statement, leading candidates to choose Option C, but in reality the expression after the colon is automatically returned.

How to eliminate wrong answers

Option B is wrong because it is syntactically identical to Option A, but the question asks for 'which of the following lambda expressions is correct' and only one answer is marked as correct; in this context, Option B is a duplicate and not the intended correct choice. Option C is wrong because it uses `return` inside a lambda, which is invalid syntax — lambda bodies can only contain a single expression, not a statement like `return`. Option D is wrong because it is a regular function definition using `def`, not a lambda expression, so it does not meet the requirement of being a lambda.

385
MCQmedium

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

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

85 satisfies the second if-elif.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

386
MCQmedium

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

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

Correct outputs.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

387
Multi-Selectmedium

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

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

Converts string to integer.

Why this answer

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

Exam trap

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

388
Multi-Selectmedium

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

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

tuple is a built-in immutable sequence type.

Why this answer

list, tuple, and set are built-in data types. array is from the array module, and dictionary is not a type name (the type is dict).

389
MCQeasy

What is the output from the interactive Python session?

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

390
MCQhard

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

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

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

Why this answer

Option A uses setdefault with a condition; setdefault only adds if key is missing, and the condition ensures it's added only when debug is False. Option B adds timeout when debug is True, opposite of requirement. Option C uses update, which adds or overwrites, but condition is correct; however, update does not check existence first, so if timeout already exists, it would overwrite, but requirement says 'if it does not already exist', setdefault is more appropriate.

Option D's use of setdefault on 'debug' returns its value (True) so condition false, but also setdefault would add 'debug' key if missing, which is not intended. Thus A is best.

391
Drag & Dropmedium

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

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

Steps
Order

Why this order

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

392
MCQmedium

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

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

Correct values.

Why this answer

Option A is correct: 3/2 = 1.5, 3//2 = 1 (floor division), 3%2 = 1 (remainder). Option B has e=0 wrong. Option C has c=1 wrong.

Option D has d=1.5 wrong.

393
MCQhard

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

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

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

Why this answer

The lambda captures the variable i by reference, not by value. Since i ends up as 2 after the loop, all lambdas return 2. Option B is correct.

Option A is wrong because of late binding. Options C and D are incorrect.

394
MCQhard

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

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

Correct; expression evaluates to True.

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

395
Multi-Selectmedium

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

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

Correct; converts list to tuple.

Why this answer

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

Exam trap

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

396
Multi-Selectmedium

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

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

Standard dictionary literal.

Why this answer

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

Exam trap

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

397
MCQhard

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

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

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

Why this answer

Option A is correct: the generator expression creates items on the fly, but then list() consumes it to produce a list, still holding all in memory. So no improvement. Option B is correct: a loop with list.append is memory-equivalent to a list comprehension.

Option C is correct: changing to a generator only postpones the problem because later operations require a list. Option D is the correct approach: lazily produce results using a generator, and only convert to list at the very end if necessary. If the subsequent processing can also work with an iterator, you can avoid the list entirely.

The best solution is to change the whole processing pipeline to use iterators, not just one part.

398
Matchingmedium

Match each Python operator to its description.

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

Concepts
Matches

Equality comparison operator

Inequality comparison operator

Floor division operator

Modulus (remainder) operator

Exponentiation operator

Why these pairings

These are common operators in Python for arithmetic and comparison.

399
MCQmedium

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

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

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

Why this answer

Default arguments are evaluated only once at function definition. The same list is used each call. The first call returns [1], the second returns [1,1].

Option B is correct. Option A is wrong because the list is mutated. Option C is wrong because the second call adds to the same list.

Option D is wrong because no TypeError occurs.

400
MCQhard

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

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

Converts input to float, allows multiplication.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

401
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

402
Multi-Selecthard

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

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

Default iteration over keys.

Why this answer

Options B, C, D are correct. B: items() returns key-value pairs. C: keys() with index d[k] works.

D: direct iteration over dictionary gives keys. A is wrong: enumerate on dict gives index, not key. E is wrong: values() gives only values.

403
MCQmedium

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

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

enumerate() provides both index and value directly.

Why this answer

enumerate() returns an iterator that yields pairs of (index, element) for each element in the iterable, making it ideal for accessing both.

404
MCQeasy

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

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

input() always returns a string.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

405
MCQmedium

What is the output of the code?

A.None
B.inf
C.2.0
D.An unhandled TypeError is raised.
AnswerA

TypeError caught, returns None.

Why this answer

Option A is correct because the code attempts to divide an integer by zero (2 / 0), which in Python raises a ZeroDivisionError. Since there is no try-except block to handle this exception, the program crashes before any value is assigned or returned, so the output is None (the default return value of a function that does not execute successfully).

Exam trap

Python Institute often tests the distinction between different exception types, and the trap here is that candidates may confuse ZeroDivisionError with TypeError or assume Python returns 'inf' like some other languages.

How to eliminate wrong answers

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

406
MCQhard

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

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

False and True = False.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

407
MCQmedium

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

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

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

Why this answer

Option B is correct following operator precedence: ** first (2**3=8), then * (4*8=32), then // (32//5=6), then + (3+6=9). Options A, C, D reflect different precedence errors.

408
Multi-Selectmedium

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

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

Triple quotes are valid for strings.

Why this answer

Option A prints the string correctly. Option B uses single quotes, prints correctly. Option C is incorrect because the backslash-escaped double quotes inside the string cause a syntax error due to mismatched quotes.

Option D is correct: triple quotes allow multiline but it prints as is. Option E is incorrect: the string has unescaped double quotes inside double quotes, causing syntax error.

409
MCQeasy

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

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

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

Why this answer

Tuples are immutable; assignment raises TypeError. Option D is correct because it is the TypeError that occurs. Option A is wrong because tuples cannot be mutated.

Option B is wrong because AttributeError is for attribute access, not assignment. Option C is wrong because ValueError is for incorrect value, not assignment.

410
MCQmedium

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

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

Conversion to int allows multiplication.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

411
Multi-Selectmedium

Which TWO of the following are valid Python variable names?

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

Letters and digits allowed.

Why this answer

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

Exam trap

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

412
MCQmedium

What will be printed?

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

All three IPs matched.

Why this answer

Option D is correct: findall returns all IP addresses in order: 192.168.1.10, 255.255.255.0, 192.168.1.1. Option A only finds first. Option B only finds subnet mask.

Option C finds two.

413
MCQmedium

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

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

int() truncates the float to the integer part.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

414
MCQmedium

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

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

Correct list comprehension with expression and filter.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

415
MCQeasy

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

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

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

Why this answer

Triple quotes (''' or """) can be used as a multi-line string, which acts as a comment when not assigned to a variable. Although it is not a true comment, it is commonly used for multi-line comments in Python.

416
MCQhard

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

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

Correct: division always returns float.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

417
MCQmedium

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

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

Correct list comprehension.

Why this answer

Option D is correct because it uses list comprehension to add 5 to each element. Option A modifies the list in place with a loop but uses wrong syntax (no range). Option B tries to add 5 to the list, not elements.

Option C tries to assign to scores but uses wrong syntax.

418
MCQeasy

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

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

Converts to uppercase.

Why this answer

Option A is correct because the upper() method returns a string in uppercase. Option B is wrong because it returns the original case. Option C is wrong because the method changes the case.

Option D is wrong because upper() does not add an exclamation mark.

419
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

420
MCQhard

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

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

Both A and C fix the error correctly.

Why this answer

Option A is correct because both B and D are valid fixes for the error shown in the exhibit. The error occurs when trying to concatenate a string with an integer using the + operator, which raises a TypeError in Python. Option B uses the comma syntax to print multiple items, which automatically converts the integer to a string for output, while Option D explicitly converts the integer to a string using str(42), allowing safe concatenation.

Option C is invalid because int() cannot convert a non-numeric string like "The answer is " to an integer.

Exam trap

Python Institute often tests the misconception that only one fix is correct, when in reality both the comma syntax and explicit str() conversion are valid solutions, and candidates may overlook the comma syntax as a legitimate alternative.

How to eliminate wrong answers

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

421
MCQeasy

Which of the following is a floating-point literal?

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

Contains a decimal point, so float.

Why this answer

Option B is correct because '3.14' is a float literal. Option A is an integer. Option C is a complex number.

Option D is a string.

422
MCQhard

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

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

Updating the condition variable prevents infinite loops.

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

423
MCQeasy

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

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

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

Why this answer

The code first assigns b's value (10) to a, so a becomes 10. Then b is assigned the value of a (which is now 10), so b becomes 10. Thus both a and b are 10.

424
MCQeasy

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

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

All three snippets produce the same list.

Why this answer

All three options produce the same list: Option A uses multiplication, option B filters, option C uses step. So all are correct.

425
MCQeasy

Which keyword is used to define a function in Python?

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

Standard keyword for function definition.

Why this answer

Option A is correct: 'def' defines a function. Option B 'function' is not a keyword. Option C 'define' is not a keyword.

Option D 'func' is not a keyword.

426
MCQmedium

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

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

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

Why this answer

Option D is correct because reading the file line by line using a for loop is already efficient; the slowness might be due to other issues like excessive splitting or string operations. Option A is wrong because readlines() loads the entire file into memory, which could be worse. Option B is wrong if the script already reads efficiently.

Option C is wrong because 'rb' mode does not help with counting lines of text.

427
Multi-Selecteasy

Which THREE of the following are characteristics of Python tuples?

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

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

Why this answer

Tuples are ordered (B), can be hashable if their elements are hashable (C), and can contain duplicate values (E). Tuples are immutable, so they do not support item assignment (D is false) and are not mutable (A is false).

428
MCQhard

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

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

ValueError caught, then finally.

Why this answer

Option C is correct: int('hello') raises ValueError, so x=0, then finally adds 1 -> x=1. Option A ignores finally. Option B ignores exception handling.

Option D incorrectly assumes TypeError.

429
MCQmedium

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

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

This would allow processing all numbers, not stopping at -1.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

430
MCQeasy

What is the result of 17 % 5 in Python?

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

Correct remainder of 17/5

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

431
MCQeasy

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

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

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

Why this answer

Option B (config.get(key, 'N/A')) is the most efficient and readable approach. It directly returns the default if the key is missing, without raising an exception or performing multiple lookups. Option A uses try-except, which is less efficient and more verbose.

Option C uses setdefault, which modifies the dictionary by adding the default key-value pair, which may not be desired. Option D requires an extra lookup and is more verbose.

432
MCQhard

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

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

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

Why this answer

Option C is correct: division by zero raises ZeroDivisionError, caught by except, prints 'error', then finally block always runs, prints 'done'. Option A misses the error message. Option B misses finally.

Option D reverses order.

433
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

434
MCQhard

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

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

Counter is optimized for frequency counting.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

435
MCQhard

What is the output of the code?

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

Correct: Alice prints because age>=26; Bob prints 'Check' from else.

Why this answer

The code uses a for loop to iterate over a list of names. For each name, it checks if the length of the name is less than 5. 'Alice' has length 5, so the condition is false and the loop continues to the next iteration without printing anything. 'Bob' has length 3, which is less than 5, so 'Bob' is printed. After the loop, the code prints 'Check'.

Therefore, the output is 'Bob' followed by 'Check' on separate lines. Option A is correct because it matches this output.

Exam trap

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

How to eliminate wrong answers

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

436
Multi-Selecthard

Which THREE of the following are arithmetic operators in Python?

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

Floor division operator.

Why this answer

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

Exam trap

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

437
MCQhard

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

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

Correct concatenation.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

438
MCQeasy

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

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

2 ** 3 = 2^3 = 8.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

439
MCQhard

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

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

Correct: get with fallback handles both key casings.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

440
Drag & Dropmedium

Arrange the steps to slice a list in Python.

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

Steps
Order

Why this order

List slicing uses start:stop:step syntax within brackets.

441
MCQhard

Given the exhibit, what does the code print?

A.3.0
B.3
C.3.5
D.3.5
AnswerA

Correct: floor division of float yields float.

Why this answer

The code `print(7 // 2)` uses the floor division operator `//`, which divides the left operand by the right operand and returns the largest integer less than or equal to the result. Since 7 divided by 2 equals 3.5, the floor of 3.5 is 3.0 (as a float because one operand is a float in Python 3? Actually both are integers, so `//` returns an integer, but the output is `3` not `3.0`. Wait—the exhibit likely shows `print(7 / 2)`? No, the question says 'Given the exhibit' but the exhibit is not shown; however, based on the correct answer being '3.0', the code must be `print(7 / 2)` which returns 3.5? No, 3.0 suggests floor division with a float result? Actually in Python 3, `7 / 2` returns 3.5, not 3.0.

The only way to get 3.0 is `7 // 2` if one operand is a float, e.g., `7.0 // 2` returns 3.0. Or the exhibit shows `print(7 // 2)` and the answer is 3 (integer), but the correct answer is listed as 3.0. This is inconsistent.

Given the answer options, the correct answer is A: 3.0, so the code must be `print(7.0 // 2)` or `print(7 // 2.0)`. The floor division with a float operand returns a float. Thus the code prints 3.0.

Exam trap

Python Institute often tests the distinction between `/` (true division returning a float) and `//` (floor division) and the type of the result depending on operand types, tricking candidates who forget that a float operand yields a float result.

How to eliminate wrong answers

Option B (3) is wrong because if the code used integer floor division `7 // 2`, the result would be the integer 3, not 3.0; but the correct answer is 3.0, so the code must involve a float operand. Option C (3.5) is wrong because it represents the result of true division `/` (e.g., `7 / 2`), not floor division `//`. Option D (3.5) is identical to C and also wrong for the same reason.

442
MCQmedium

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

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

Clear and explicit guard condition.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

443
MCQeasy

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

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

Correct and efficient; skips non-positive.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

444
MCQmedium

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

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

No type restrictions.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

445
Multi-Selectmedium

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

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

3 squared equals 9.

Why this answer

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

Exam trap

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

446
MCQeasy

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

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

Correct. 5 + 3.0 = 8.0, a float.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

447
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

448
MCQhard

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

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

This file marks the directory as a Python package.

Why this answer

For a directory to be treated as a package, it must contain an __init__.py file (though optional in Python 3.3+ for namespace packages, it is required for regular packages).

449
MCQeasy

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

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

Correct conversion.

Why this answer

The input() function returns a string, so you must convert it using int(). Option B is correct.

Page 5

Page 6 of 7

Page 7

All pages