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

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

Page 1

Page 2 of 7

Page 3
76
MCQhard

A junior developer is working on a script that processes user data. The script reads a CSV file into a list of dictionaries. Each dictionary represents a user with keys 'name', 'age', and 'email'. The developer needs to filter out users under 18 and store their names in a list. The current code is: users = [{'name': 'Alice', 'age': 17, 'email': 'alice@example.com'}, {'name': 'Bob', 'age': 22, 'email': 'bob@example.com'}] minors = [] for user in users: if user['age'] < 18: minors.append(user['name']) print(minors) The code works, but the senior developer says it is not idiomatic and suggests a more concise solution. Which of the following approaches is the best replacement?

A.minors = [] for i in range(len(users)): if users[i]['age'] < 18: minors.append(users[i]['name'])
B.minors = [user for user in users if user['age'] < 18]
C.minors = list(map(lambda u: u['name'], filter(lambda u: u['age'] < 18, users)))
D.minors = [user['name'] for user in users if user['age'] < 18]
AnswerD

Concise and idiomatic list comprehension.

Why this answer

Option D is correct because it uses a list comprehension to directly extract the 'name' field from each user dictionary where the age is under 18, making the code concise and Pythonic. The original code works but is verbose; list comprehensions are the idiomatic Python approach for transforming and filtering iterables in a single readable line.

Exam trap

Python Institute often tests the distinction between filtering entire objects versus extracting specific fields, so candidates may pick Option B (which filters dictionaries) instead of Option D (which extracts the 'name' field), missing the requirement to store only names.

How to eliminate wrong answers

Option A is wrong because it uses an index-based loop with range(len(users)), which is less readable and not Pythonic; it also does not extract the 'name' field, appending the entire dictionary instead. Option B is wrong because it creates a list of entire user dictionaries (not just names), failing to meet the requirement of storing only names. Option C is wrong because it uses map() and filter() with lambda functions, which is unnecessarily complex and less readable than a list comprehension, though it would produce the correct result; it is not the best replacement for simplicity and Pythonic style.

77
MCQmedium

You are writing a script to parse a log file. Each line in the log contains a timestamp and a message separated by a colon. You need to extract only the messages that contain the word 'ERROR'. The script uses a list comprehension to filter lines. However, the script crashes with a 'ValueError: not enough values to unpack' when processing some lines. The code is: lines = ['2024-01-01 12:00:00: INFO: all good', '2024-01-01 12:01:00: ERROR: something wrong'] errors = [msg for timestamp, msg in line.split(': ') for line in lines if 'ERROR' in msg] What is the correct fix?

A.Rewrite as: [line for line in lines if 'ERROR' in line]
B.Change the list to a dictionary
C.Swap the order of the for clauses to: [msg for line in lines for timestamp, msg in line.split(': ') if 'ERROR' in msg]
D.Rewrite as: [msg for line in lines if 'ERROR' in line for msg in [line.split(': ')[1]]]
AnswerD

Correct nested comprehension.

Why this answer

Option D is correct because it properly separates the filtering and unpacking steps. The original code attempts to unpack each line into timestamp and msg using `line.split(': ')`, but some lines may not contain exactly two parts after splitting (e.g., if the colon is missing or there are extra colons), causing a ValueError. Option D first filters lines containing 'ERROR', then safely extracts the message part by splitting and taking index [1] inside a nested comprehension, avoiding the unpacking error.

Exam trap

Python Institute often tests the order of `for` clauses in nested list comprehensions and the assumption that `split()` always returns a fixed number of parts, leading candidates to choose Option C which only reorders loops without fixing the unpacking error.

How to eliminate wrong answers

Option A is wrong because it returns the entire line as a string, not just the message part after the colon, so it does not meet the requirement of extracting only the messages. Option B is wrong because converting the list to a dictionary does not solve the unpacking issue; the original code would still crash on lines that cannot be split into exactly two parts. Option C is wrong because swapping the for clauses does not fix the fundamental problem: `line.split(': ')` still returns a list that may not have exactly two elements, and unpacking it into timestamp, msg will raise a ValueError if the split result has a different length.

78
Multi-Selecteasy

Which two of the following list methods modify the original list in place? (Choose two.)

Select 2 answers
A.sort()
B.count()
C.sorted()
D.append()
E.copy()
AnswersA, D

Sorts the list in place.

Why this answer

A is correct because the `sort()` method sorts the list in place, meaning it modifies the original list object without creating a new one. D is correct because `append()` adds an element to the end of the list, directly mutating the original list.

Exam trap

Python Institute often tests the distinction between methods that mutate the list in place (like `sort()`) and functions that return a new list (like `sorted()`), as well as the fact that `count()` and `copy()` are non-mutating, to see if candidates confuse method behavior with function behavior.

79
MCQmedium

A Python script reads this JSON and needs to check if port 8080 is allowed. Which expression correctly checks? Assume data is already parsed into a dictionary.

A.data["ports"].contains(8080)
B.data.get("ports") == 8080
C.8080 in data["ports"]
D."ports" in data
AnswerC

Correct; checks if 8080 is in the list.

Why this answer

Option C is correct because the `in` operator checks for membership in a list. Since `data["ports"]` is a list (e.g., `[80, 443, 8080]`), `8080 in data["ports"]` returns `True` if 8080 is present. This directly tests whether port 8080 is allowed.

Exam trap

Python Institute often tests the distinction between checking for a key in a dictionary (`key in dict`) versus checking for a value in a list (`value in list`), and candidates mistakenly use `contains()` (from Java or other languages) or confuse dictionary key existence with list membership.

How to eliminate wrong answers

Option A is wrong because `contains()` is not a built-in method for Python lists; the correct method is `list.count()` or the `in` operator. Option B is wrong because `data.get("ports")` returns the entire list, not a single integer, so comparing it with `== 8080` will always be `False`. Option D is wrong because `"ports" in data` checks if the key `"ports"` exists in the dictionary, not whether port 8080 is in the list of allowed ports.

80
Multi-Selecthard

Which THREE of the following statements about Python data types are correct? (Choose three.)

Select 3 answers
A.Strings are mutable.
B.Sets are immutable.
C.Tuples are immutable.
D.Lists are mutable.
E.Dictionaries are mutable.
AnswersC, D, E

Tuples cannot be changed after creation.

Why this answer

Option C is correct because tuples in Python are immutable, meaning once created, their elements cannot be changed, added, or removed. This immutability makes tuples hashable and usable as dictionary keys, unlike lists.

Exam trap

The trap here is that candidates often confuse the immutability of strings and tuples with the mutability of lists and dictionaries, or incorrectly assume sets are immutable because their elements must be immutable.

81
MCQmedium

A developer needs to iterate over the indices of a list named 'items' and print each index and its corresponding value. Which loop construct is most appropriate?

A.for val in items: print(items.index(val), val)
B.for i in range(len(items)): print(i, items[i])
C.for i, val in enumerate(items): print(i, val)
D.for i in items: print(i)
AnswerC

Pythonic and direct.

Why this answer

Option C is correct because `enumerate(items)` returns an iterator that yields pairs of (index, value) directly, making it the most Pythonic and efficient way to iterate over both indices and values of a list. It avoids the overhead of calling `items.index(val)` (which is O(n) per iteration) or manually managing `range(len(items))`.

Exam trap

Python Institute often tests the distinction between iterating over values (`for val in items`) versus indices (`for i in range(len(items))`) versus both (`enumerate`), and the trap here is that candidates may choose Option B because it works, missing that `enumerate` is the idiomatic and recommended construct for this exact use case.

How to eliminate wrong answers

Option A is wrong because `items.index(val)` performs a linear search for each element, which is inefficient (O(n²) overall) and will return the first occurrence of the value, not necessarily the current index if duplicates exist. Option B is wrong because while it technically works, it is less Pythonic and more verbose than `enumerate`; it requires manual indexing and is prone to off-by-one errors if the list length changes. Option D is wrong because it iterates over the values themselves, not the indices, so it prints each value as if it were an index, which is semantically incorrect for the requirement.

82
MCQhard

A developer needs to check if a variable x is between 10 and 20 (inclusive). Which expression is correct?

A.x > 10 and x < 20
B.x < 10 and x < 20
C.10 <= x <= 20
D.x >= 10 or x <= 20
AnswerC

Chained comparison works exactly as desired.

Why this answer

Option C is correct because Python supports chained comparison operators, allowing `10 <= x <= 20` to evaluate whether `x` is between 10 and 20 inclusive. This expression is equivalent to `(10 <= x) and (x <= 20)`, which checks both boundaries simultaneously.

Exam trap

The trap here is that candidates often confuse inclusive vs. exclusive boundaries and select Option A with strict inequalities, or they misunderstand that `or` (Option D) creates a condition that is always true, failing to recognize the need for `and` logic.

How to eliminate wrong answers

Option A is wrong because it uses strict inequality operators (`>` and `<`), which exclude the boundary values 10 and 20, so it checks for values strictly between 10 and 20, not inclusive. Option B is wrong because `x < 10 and x < 20` is equivalent to `x < 10`, which only checks if x is less than 10, completely missing the upper bound and the inclusive requirement. Option D is wrong because the `or` operator means the condition is true if x is either greater than or equal to 10 OR less than or equal to 20, which is always true for any real number, making it a tautology.

83
Multi-Selecteasy

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

Select 2 answers
A.value_2
B.value-2
C.2nd_value
D._value
E.for
AnswersA, D

Valid identifier.

Why this answer

Variable names cannot start with a digit, cannot contain hyphens, and cannot be reserved keywords. _value and value_2 are valid.

84
MCQeasy

A developer wrote: a, b, c = 10, 20, 30; avg = a + b + c / 3; print(avg). What is the output?

A.60.0
B.20.0
C.40.0
D.30.0
AnswerC

Correct: 10 + 20 + (30/3) = 40.

Why this answer

Division has higher precedence than addition, so c/3 = 10, then a+b+10 = 40.0. Option C is correct.

85
MCQhard

Which of the following is the most efficient (Pythonic) way to create a list of squares for numbers 0 through 9?

A.squares = [i*i for i in range(10)]
B.squares = []; for i in range(10): squares.append(i*i)
C.squares = list(map(lambda x: x*x, range(10)))
D.squares = (i*i for i in range(10))
AnswerA

List comprehension is preferred.

Why this answer

Option C is correct because list comprehension is concise and Pythonic. Option A is wrong because appending in a loop is less efficient. Option B is wrong because map requires a lambda and is less readable.

Option D is wrong because it uses a generator expression which doesn't produce a list directly.

86
Multi-Selectmedium

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

Select 3 answers
A.str
B.int
C.float
D.list
E.dict
AnswersA, B, C

Immutable.

Why this answer

Option A is correct because strings (str) in Python are immutable, 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 in memory, leaving the original unchanged.

Exam trap

Python Institute often tests the misconception that all numeric types are mutable or that strings can be changed in place, leading candidates to incorrectly select list or dict as immutable.

87
MCQhard

A network engineer uses bitwise operators to set flags for packet filtering. The variable 'flags' currently holds the integer 10 (binary 1010). To enable the second bit (value 2) and disable the fourth bit (value 8), which expression should be used?

A.flags = flags | 2
B.flags = flags ^ 10
C.flags = flags & ~8
D.flags = (flags | 2) & ~8
AnswerD

Correctly sets bit 1 and clears bit 3

Why this answer

Option D is correct because it combines two operations in a single expression: first, it sets the second bit (value 2) using the bitwise OR (|) operator, which turns on that bit without affecting others; second, it clears the fourth bit (value 8) using the bitwise AND with the complement of 8 (& ~8), which forces that bit to 0. This achieves the required flag state: binary 1010 becomes 0010 (decimal 2).

Exam trap

Python Institute often tests the misconception that a single operator (like OR or AND alone) can both set and clear bits, leading candidates to pick Option A or C, when in reality you must combine both operations to independently control different bits.

How to eliminate wrong answers

Option A is wrong because it only sets the second bit (flags = flags | 2) but does not disable the fourth bit, leaving the result as 1010 (10) unchanged since bit 2 is already set. Option B is wrong because XOR with 10 (binary 1010) toggles bits: it would flip the second bit (0→1) and the fourth bit (1→0), resulting in 0000 (0), which disables the fourth bit but also incorrectly toggles other bits, not matching the requirement to only enable bit 2 and disable bit 4. Option C is wrong because it only clears the fourth bit (flags = flags & ~8) but does not enable the second bit, leaving the result as 0010 (2) if the second bit was already set, but if it were not set, it would remain 0; in this case, flags is 10 (1010), so bit 2 is already 1, but the expression does not guarantee enabling it if it were 0.

88
Multi-Selectmedium

Which TWO of the following are true about function arguments in Python? (Choose two.)

Select 2 answers
A.Arguments can be passed by position or keyword.
B.Default arguments are evaluated each time the function is called.
C.*args collects keyword arguments.
D.**kwargs collects positional arguments.
E.Default arguments are evaluated at function definition time.
AnswersA, E

Correct: Python supports both positional and keyword arguments.

Why this answer

Default arguments are evaluated at definition time (A). Arguments can be passed by position or keyword (C). Options B, D, E are false.

89
MCQmedium

What is the output of the code?

A.No output
B.0 1 2 3 4
C.0 1 2 4
D.0 1 2 4 5
AnswerC

Correct: 3 is skipped.

Why this answer

The code uses a for loop with range(5) to iterate over numbers 0 through 4. Inside the loop, an if statement checks if the current number equals 3; if true, the break statement exits the loop immediately. Therefore, when i becomes 3, the loop terminates before printing 3, so the output is '0 1 2' (each on a new line due to print(i) default behavior).

Option C correctly lists the printed values as 0, 1, 2, and then 4 is not printed because the loop breaks before reaching 4.

Exam trap

Python Institute often tests the interaction between break and loop iteration order, where candidates mistakenly think break skips only the current iteration (like continue) or that the loop continues after the break condition is met.

How to eliminate wrong answers

Option A is wrong because the loop does produce output: it prints 0, 1, and 2 before the break occurs. Option B is wrong because it includes 3 and 4, but the break at i == 3 prevents printing 3 and any subsequent numbers. Option D is wrong because it includes 5, but the range(5) generates numbers 0-4, so 5 is never reached, and the break also stops before 4 is printed.

90
MCQmedium

Which operator is used to check if two values are equal in Python?

A.=
B.eq
C.!=
D.==
AnswerD

Equality comparison.

Why this answer

Option D is correct because the == operator is Python's equality comparison operator, used to check if two values are equal. It returns True if the values are equal and False otherwise, making it the standard way to test equality in conditions and expressions.

Exam trap

Python Institute often tests the confusion between the assignment operator = and the equality operator ==, as beginners mistakenly use = in conditions like if x = 5 instead of if x == 5, which causes a syntax error or unintended assignment.

How to eliminate wrong answers

Option A is wrong because = is the assignment operator in Python, used to assign a value to a variable, not to compare values. Option B is wrong because eq is not a built-in operator in Python; while some objects may have an __eq__() method for custom equality, eq alone is not a valid operator. Option C is wrong because != is the inequality operator, which checks if two values are not equal, the opposite of what the question asks.

91
MCQeasy

A user enters 5 at the prompt. What is printed?

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

String '5' repeated twice.

Why this answer

Option C is correct: input returns a string '5', so '5' * 2 = '55'. Option A would be if input was converted to int. Option B if multiplication with string.

Option D if no output.

92
MCQeasy

Which operator performs integer (floor) division in Python?

A.//
B.%
C./
D.**
AnswerA

Correct operator for integer division.

Why this answer

The // operator performs integer (floor) division in Python, which divides two numbers and returns the largest integer less than or equal to the result. For example, 7 // 2 returns 3, not 3.5, because it discards the fractional part and rounds down toward negative infinity for negative numbers.

Exam trap

Python Institute often tests the distinction between / (true division) and // (floor division), trapping candidates who assume / performs integer division as in some other languages like C or Java.

How to eliminate wrong answers

Option B (%) is wrong because it is the modulo operator, which returns the remainder of a division, not the quotient. Option C (/) is wrong because it performs true (floating-point) division, always returning a float result (e.g., 7 / 2 = 3.5). Option D (**) is wrong because it is the exponentiation operator, used for raising a number to a power (e.g., 2 ** 3 = 8).

93
MCQeasy

What is the output of the code?

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

Correct: prints 1, then 2, then loop ends.

Why this answer

The code uses a `for` loop with `range(1, 4)` which generates the sequence 1, 2, 3. Inside the loop, `if i == 3: break` causes the loop to terminate when `i` equals 3, so the loop only prints 1 and 2 before breaking. After the loop, `print('Done')` is executed because it is outside the loop, so the output is 1, 2, and Done on separate lines.

Exam trap

Python Institute often tests the distinction between `break` and `continue`, and the trap here is that candidates forget that `break` exits the loop entirely, not just the current iteration, leading them to incorrectly include the value that triggered the break in the output.

How to eliminate wrong answers

Option A is wrong because it omits 'Done' and shows only 1 and 2, but the code prints 'Done' after the loop. Option B is wrong because it prints 3 before 'Done', but the `break` statement prevents 3 from being printed. Option D is wrong because it prints 1, 2, 3 without 'Done', but the code includes `print('Done')` after the loop.

94
MCQhard

A critical automation system uses a try-except block to handle errors during file operations. The current code uses a bare except: clause to catch any error and perform cleanup. However, when an operator tries to stop the program with Ctrl+C, the KeyboardInterrupt exception is caught, and the cleanup routine runs, preventing a clean exit. Additionally, if the system runs out of memory, MemoryError is caught. The developers need to modify the exception handling so that system-exiting exceptions (such as KeyboardInterrupt and SystemExit) are not caught, but other exceptions (e.g., FileNotFoundError, PermissionError) are still handled for cleanup. Which modification best achieves this?

A.Change the bare except: to except Exception:
B.Remove the except block entirely and rely on a finally block for cleanup
C.Replace the single except block with multiple specific except blocks for each expected file error
D.Define a custom exception class and raise it for all file errors
AnswerA

except Exception: catches all exceptions that inherit from Exception, excluding KeyboardInterrupt and SystemExit.

Why this answer

Option A (change to except Exception) is the standard way to avoid catching KeyboardInterrupt and SystemExit because those exceptions inherit from BaseException, not Exception. This will catch all other exceptions that are likely to occur in file operations. Option B (multiple specific except blocks) is too restrictive and may miss unexpected errors.

Option C (using finally) does not replace the except block and will still execute cleanup even if the exception is not caught, which may not be desired. Option D (custom exception class) is unnecessary.

95
MCQmedium

Refer to the exhibit. What is the output?

A.5
B.2
C.9
D.1
AnswerD

After bubble sort, the smallest element is at index 0.

Why this answer

The correct answer is D (1) because the code uses a for loop to iterate over the list [1, 2, 3, 4, 5] and breaks out of the loop when the current element equals 3. The variable 'x' is assigned the value of the last element processed before the break, which is 2, but the print statement is outside the loop and prints the final value of 'x' after the loop ends, which is 2. However, the code snippet in the exhibit likely has a different logic: if the loop iterates and breaks at 3, then 'x' is 2, but the output is 1 because the loop starts at 1 and the break condition is met immediately, so 'x' remains 1.

The correct output is 1.

Exam trap

The trap here is that candidates often assume the loop variable holds the value that triggered the break, but it actually holds the value from the previous iteration, leading to off-by-one errors in output prediction.

How to eliminate wrong answers

Option A (5) is wrong because it assumes the loop completes all iterations without breaking, but the break statement exits the loop when the condition is met, so the last value of 'x' is not 5. Option B (2) is wrong because it assumes the loop processes up to the element before the break, but the break occurs at the first element (1) if the condition is 'x == 1', so 'x' is never updated to 2. Option C (9) is wrong because it is not a value present in the list or derived from the loop logic; it likely results from a misunderstanding of the loop range or break behavior.

96
MCQeasy

Based on the exhibit, which expression returns 2.5 in Python?

A.int(5 / 2)
B.5 % 2
C.5 // 2
D.5 / 2
AnswerD

True division returns 2.5.

Why this answer

Option D is correct because the division operator `/` in Python always returns a float, even when dividing two integers. Since 5 divided by 2 equals 2.5, the expression `5 / 2` returns the float `2.5`.

Exam trap

Python Institute often tests the distinction between `/` (true division returning float) and `//` (floor division returning integer), trapping candidates who confuse the two or expect integer division from `/` as in Python 2.

How to eliminate wrong answers

Option A is wrong because `int(5 / 2)` first computes `5 / 2` to get `2.5`, then `int()` truncates the decimal part, returning the integer `2`, not `2.5`. Option B is wrong because the modulo operator `%` returns the remainder of the division, which is `1` (since 5 divided by 2 gives quotient 2 and remainder 1), not `2.5`. Option C is wrong because the floor division operator `//` performs integer division and returns the integer quotient `2` (truncating toward negative infinity for positive numbers), not `2.5`.

97
MCQhard

A developer is writing a robust script that must handle file reading errors. The script should catch only I/O-related exceptions (e.g., FileNotFoundError, PermissionError) and let other exceptions propagate. Which exception handling structure is best suited?

A.Use a single bare except: clause
B.Use except: and then re-raise the exception
C.Use multiple except blocks for specific exception types
D.Use except Exception: as the only handler
AnswerC

This targets only the expected exceptions, letting others propagate as intended.

Why this answer

Option D is correct because using multiple except blocks for specific exception types allows precise handling without catching unwanted exceptions. Option A and C use bare except or except: which catch SystemExit and KeyboardInterrupt, which is dangerous. Option B catches all exceptions that inherit from Exception, which is too broad and may catch unexpected errors.

98
MCQhard

A developer is implementing a toggle switch feature. The variable flag starts as False. Which code snippet correctly toggles the flag and performs an action based on the new value each time the code is run? (Assume action1 is performed when flag is True, action2 when False.)

A.flag = not flag; if flag: action1() else: action2()
B.if not flag: flag = True; action1() else: flag = False; action2()
C.if flag: flag = False; action1() else: flag = True; action2()
D.flag = not flag; if flag: action2() else: action1()
AnswerA

Correctly toggles then uses new value.

Why this answer

Option A is correct because it first toggles the flag using `flag = not flag`, which flips the boolean value from False to True (or vice versa). Then it uses a conditional `if flag:` to check the new value and calls `action1()` when True or `action2()` when False, exactly matching the requirement to act on the new state each time the code runs.

Exam trap

Python Institute often tests the order of operations in toggle-and-check patterns, where candidates mistakenly perform the action based on the old flag value instead of the new one after toggling.

How to eliminate wrong answers

Option B is wrong because it checks `if not flag:` first, then sets `flag = True` and calls `action1()` — but when `flag` is False, it toggles to True and runs `action1()` (correct for True), but the `else` branch sets `flag = False` and calls `action2()` — this logic is inverted: it runs `action1()` when the new flag is True but the structure is confusing and the else branch incorrectly sets flag to False when it was already True, failing to toggle properly. Option C is wrong because it checks `if flag:` first, then sets `flag = False` and calls `action1()` — this runs `action1()` when the new flag is False (since it just set it to False), which is the opposite of the requirement (action1 should run when flag is True). Option D is wrong because it correctly toggles the flag with `flag = not flag`, but then checks `if flag:` and calls `action2()` instead of `action1()`, swapping the actions — so when flag becomes True, it incorrectly runs `action2()`.

99
MCQhard

A team observes that the following code prints 'Found' even when the item is not in the list. Code: for item in mylist: if item == target: print('Found'); break; else: print('Not found'). Which modification ensures it correctly prints 'Not found' only if the item is not present?

A.Move else inside the if block
B.Replace break with continue
C.Use a flag variable to track found status
D.Align the else with the for statement (for-else construct)
AnswerD

Correct: for-else executes else only if no break occurred.

Why this answer

Option D is correct because the original code uses a for-else construct where the else block executes after the loop completes normally (i.e., without a break). However, the code has a syntax error: the else is incorrectly indented as part of the if statement, causing it to execute on every iteration when the condition is false. Aligning the else with the for statement (for-else construct) ensures the else block runs only if the loop finishes without hitting a break, which occurs when the item is not found.

Exam trap

Python Institute often tests the for-else construct by presenting code where the else is incorrectly indented under the if, leading candidates to think the else belongs to the if statement, when in fact the intended behavior requires the else to be aligned with the for.

How to eliminate wrong answers

Option A is wrong because moving the else inside the if block would cause it to execute only when item == target is true, printing 'Not found' incorrectly when the item is found, and never printing it when the item is not present. Option B is wrong because replacing break with continue would prevent the loop from exiting upon finding the item, causing the else block (if properly aligned) to never execute and the loop to continue iterating, potentially printing 'Found' multiple times and never printing 'Not found'. Option C is wrong because while using a flag variable could work, it is not the modification described in the question; the question asks which modification ensures correct behavior, and the for-else construct is the direct, Pythonic fix that avoids unnecessary extra variables.

100
MCQmedium

A system administrator is writing a Python script to monitor disk usage. The script uses the psutil library (not part of PCEP scope, but the scenario is generic). The administrator writes: import psutil disk = psutil.disk_usage('/') print(disk.free) But the script fails with an ImportError because psutil is not installed. The administrator decides to handle this gracefully: if the module is missing, the script should print a custom error message and exit without crashing. Which code snippet achieves this?

A.try: import psutil except ImportError: print('psutil not installed. Please install.') sys.exit(1)
B.import psutil if not psutil: print('psutil not installed.') sys.exit(1)
C.try: import psutil except ImportError: print('psutil not installed. Please install.')
D.try: import psutil except: print('Module missing.') raise
AnswerA

Catches ImportError and exits gracefully.

Why this answer

Option A is correct because it uses a try-except block to catch the ImportError specifically when the import statement fails. This allows the script to print a custom error message and then call sys.exit(1) to terminate gracefully with a non-zero exit code, which is the standard way to signal failure in a script. The other options either do not handle the missing module correctly or fail to exit the script properly.

Exam trap

Python Institute often tests the distinction between handling an exception with a graceful exit versus merely printing a message and continuing, or re-raising the exception, which still causes a crash; candidates may overlook the need for sys.exit(1) or mistakenly think a bare except or a falsy check on the module name is sufficient.

How to eliminate wrong answers

Option B is wrong because it attempts to check if the module is falsy after import, but if the import fails, the script will crash with an ImportError before reaching the if statement; Python does not assign a falsy value to a failed import. Option C is wrong because it catches the ImportError and prints a message but does not call sys.exit(1), so the script would continue executing after the except block, potentially causing further errors or undefined behavior. Option D is wrong because it uses a bare except clause (which is too broad and can mask unrelated errors) and then calls raise, which re-raises the caught exception, causing the script to crash with a traceback instead of exiting gracefully with a custom message.

101
MCQeasy

A program asks for the user's age and then prints a message: age = input("How old are you? "); print("You are " + age + " years old."). A user enters "twenty five" and the program prints "You are twenty five years old." which is not the intended numeric age. The requirement is to ensure only numeric ages are accepted and to convert the input to an integer. Which modification is the best?

A.Use try-except to catch ValueError and print an error message, then exit.
B.Check if age.isdigit() before converting, and if not, ask again.
C.Assume the user will always enter a number; no changes needed.
D.Use a try-except in a loop to repeatedly ask until valid integer is entered: while True: try: age = int(input("How old are you? ")) break except ValueError: print("Invalid.")
AnswerD

Correct; robustly handles all non-integer inputs.

Why this answer

Option D is correct because it uses a `while True` loop with a `try-except` block to repeatedly prompt the user until a valid integer is entered. The `int()` conversion raises a `ValueError` for non-numeric strings like "twenty five", and the `except` clause catches that error and prints "Invalid." without breaking the loop, ensuring only numeric ages are accepted and converted to an integer.

Exam trap

The trap here is that candidates often choose Option B (isdigit) thinking it is sufficient, but they overlook that `isdigit()` does not handle spaces or negative numbers and does not loop to re-prompt, while the correct solution must combine error handling with a loop to meet the requirement of repeatedly asking until valid input is provided.

How to eliminate wrong answers

Option A is wrong because it uses `try-except` to catch `ValueError` and then exits the program, which does not meet the requirement to keep asking until a valid numeric age is entered; it only handles the error once and terminates. Option B is wrong because `age.isdigit()` returns `False` for strings with spaces (like "twenty five"), but it does not handle the case where the user enters a valid numeric string with leading zeros (e.g., "025") which would pass `isdigit()` but `int()` would convert correctly; more importantly, it does not loop to re-prompt after a failed check, so the program would stop or proceed with invalid data. Option C is wrong because it assumes the user will always enter a number, which is unsafe and does not handle the given input "twenty five" — the program would print the string as-is without conversion, failing the requirement to accept only numeric ages and convert to integer.

102
MCQhard

A program checks divisibility. Which condition correctly determines if a number n is divisible by 7?

A.n / 7 == 0
B.n // 7 == 0
C.n % 7 == 0
D.n % 7 != 0
AnswerC

Correct: remainder 0 means divisible.

Why this answer

The modulo operator (%) returns the remainder of the division of n by 7. If the remainder is 0, then n is exactly divisible by 7. This is the standard way to test divisibility in Python.

Exam trap

Cisco often tests the distinction between division operators (/, //, %) and expects candidates to know that only the modulo operator (%) correctly checks divisibility, not the quotient operators.

How to eliminate wrong answers

Option A is wrong because the division operator (/) returns a float, and comparing a float to 0 will almost never be True for integer divisibility (e.g., 7/7 == 1.0, not 0). Option B is wrong because floor division (//) returns the integer quotient, which is 0 only when n is less than 7 (e.g., 5//7 == 0), not when n is divisible by 7. Option D is wrong because n % 7 != 0 is the condition for non-divisibility, the exact opposite of what is required.

103
MCQmedium

A developer needs to iterate over a list of network interfaces and print only the names that start with 'eth'. Which code should be used?

A.for i in range(len(interfaces)): if 'eth' in interfaces[i]: print(interfaces[i])
B.for iface in interfaces: if iface[:3] is 'eth': print(iface)
C.for iface in interfaces: if iface.startswith('eth'): print(iface)
D.for iface in interfaces: if 'eth' in iface: print(iface)
AnswerC

Correct; startswith checks prefix.

Why this answer

Option C is correct because the `startswith()` string method is the most direct and readable way to check if each interface name begins with the substring 'eth'. This approach avoids unnecessary slicing or substring membership checks, making the intent clear and the code efficient.

Exam trap

Python Institute often tests the distinction between `in` (substring membership) and `startswith()` (prefix matching), leading candidates to choose Option D because they think 'eth' must appear at the start, but `in` would also match names like 'xeth0'.

How to eliminate wrong answers

Option A is wrong because it uses `range(len(interfaces))` and index-based access, which is unnecessarily complex and less Pythonic; also `'eth' in interfaces[i]` checks if 'eth' appears anywhere in the string, not just at the start. Option B is wrong because it uses the `is` operator to compare strings, which checks identity (memory address) rather than equality; `is` should never be used for string value comparison. Option D is wrong because `'eth' in iface` returns True if 'eth' appears anywhere in the interface name (e.g., 'xeth0' or 'eth0backup'), not only at the beginning.

104
MCQhard

A developer runs the following code: x = 0.1; y = 0.2; print(x + y == 0.3). What is the output and why?

A.False, because the + operator is not defined for floats
B.True, because Python rounds to 0.3
C.True, because Python uses decimal arithmetic
D.False, due to floating-point precision
AnswerD

0.1+0.2 equals 0.30000000000000004, not exactly 0.3.

Why this answer

Option D is correct because floating-point numbers in Python (and most programming languages) are stored in binary (IEEE 754 double-precision), and values like 0.1 and 0.2 cannot be represented exactly. The sum 0.1 + 0.2 yields a result slightly greater than 0.3 (approximately 0.30000000000000004), so the equality comparison returns False.

Exam trap

Python Institute often tests the misconception that Python performs exact decimal arithmetic, leading candidates to expect True, when in fact the binary floating-point representation causes a small rounding error that makes the comparison False.

How to eliminate wrong answers

Option A is wrong because the + operator is fully defined for floats in Python and performs arithmetic addition. Option B is wrong because Python does not round the result of 0.1 + 0.2 to exactly 0.3; the internal binary representation causes a tiny error. Option C is wrong because Python uses binary floating-point arithmetic (IEEE 754), not decimal arithmetic; decimal arithmetic would require the decimal module.

105
MCQhard

Refer to the exhibit. What does the else clause of the inner for loop do?

A.Executes if the outer loop condition is false.
B.Executes if the inner loop is broken, meaning an even number was found.
C.Executes if the inner loop completes without break, meaning no even number in the row.
D.Executes after each iteration of the inner loop.
AnswerC

The else clause executes when the loop finishes normally (no break). Here, it appends the row if no even item was found.

106
Multi-Selectmedium

Which THREE statements about the break statement in Python are correct? (Choose three.)

Select 3 answers
A.It can be used with an optional else clause.
B.It exits the innermost loop when executed.
C.It can be used in an if statement outside any loop.
D.If used inside a loop, it prevents the loop's else clause from executing.
E.It can be used only inside a for or while loop.
AnswersB, D, E

Correct: break terminates the innermost loop immediately.

Why this answer

Option B is correct because the break statement, when executed inside a loop, immediately terminates the innermost loop it resides in, transferring control to the next statement after the loop. This is a fundamental behavior defined in Python's control flow documentation.

Exam trap

Python Institute often tests the misconception that break can be used with an optional else clause, confusing it with the loop-else construct, or that break can be used outside a loop, which leads to a SyntaxError.

107
Multi-Selecthard

A Python script contains the following code: x = [1, 2, 3] y = x y.append(4) z = x.copy() z.append(5) After execution, which TWO of the following statements are true? (Choose two.)

Select 2 answers
A.x and y refer to different list objects
B.x is equal to [1, 2, 3]
C.x is equal to [1, 2, 3, 4]
D.x is equal to [1, 2, 3, 4, 5]
E.z is equal to [1, 2, 3, 5]
AnswersC, E

y is a reference to x; appending to y modifies x.

Why this answer

Option A is correct because y is a reference to the same list as x, so x is [1,2,3,4]. Option B is false because x is modified via y. Option C is false because z is a shallow copy, so x is not affected by appending to z.

Option D is true because z is a separate copy, so z is [1,2,3,5]. Option E is false because x and y are the same object.

108
Multi-Selecthard

Which TWO of the following code snippets will produce the output 'True'? (Assume all variables are defined appropriately.)

Select 2 answers
A.x=2.0; y=2.0; print(x is y)
B.print(1 < 2 < 1)
C.print('ab' == 'ba')
D.print(3.0 == int(3.0))
E.a=256; b=256; print(a is b)
AnswersD, E

Value comparison coerces types, both equal 3.

Why this answer

Correct options are B and D. B: 'is' checks identity, and a and b point to same small integer due to caching. D: 3.0 == 3 returns True due to type coercion.

A: 'is' with different float objects returns False. C: 1 <= 2 <= 3 is chained comparison: 1<=2 and 2<=3 -> True and True -> True, but that's actually True? Wait 1 <= 2 <= 3 is True. But we need TWO correct.

Let me recalc: A) x=2.0; y=2.0; print(x is y) -> may be False because floats are not small ints; typically False. B) a=5; b=5; print(a is b) -> True due to integer caching. C) print(1 <= 2 <= 3) -> True.

D) print(3.0 == 3) -> True. E) print('ab' == 'ba') -> False. So three options give True? That's three correct, but we need exactly two.

So adjust: make C False? For example, print(1 <= 2 <= 1) -> False. Or change to something else. Let me redesign: A) print(2.0 is 2.0) -> probably False (no small float cache).

B) a=256; b=256; print(a is b) -> True (integers -5 to 256 cached). C) print(1 < 2 < 3) -> True. D) print(3.0 == int(3.0)) -> True.

E) print('abc' == 'abc') -> True. That's three. So to have exactly two, we need to make one of these false.

For C, change to 1 < 2 < 1 -> False. For D, change to 3.0 == 3 -> still True. For E, change to 'ab' == 'ba' -> False.

So then only B and D are True. That works. But careful: int(3.0) is 3, so True.

So final snippet: A) x=2.0; y=2.0; print(x is y) -> False. B) a=256; b=256; print(a is b) -> True. C) print(1 < 2 < 1) -> False.

D) print(3.0 == int(3.0)) -> True. E) print('ab' == 'ba') -> False. Thus correct: B and D.

109
MCQhard

A function receives a dictionary that may contain nested dictionaries. The function must modify the dictionary without affecting the original passed argument. Which technique ensures a complete independent copy?

A.Use copy.deepcopy() from the copy module
B.Assign the dictionary to a new variable (e.g., new_dict = original)
C.Use copy.copy() on the original dictionary
D.Use dict.copy() method
AnswerA

Deep copy recursively copies all objects, making the new dictionary completely independent.

Why this answer

Option C (use copy.deepcopy) creates a deep copy, ensuring that nested objects are also duplicated. Option A (copy.copy) creates a shallow copy; modifications to nested dictionaries still affect the original. Option B (dict.copy()) is also shallow.

Option D (direct assignment) just binds a new reference, so changes affect the original.

110
MCQmedium

A developer accidentally wrote: print('Hello' + 5). What happens?

A.It prints 'Hello' and ignores the 5
B.It prints a warning but still runs
C.It raises a TypeError
D.It prints 'Hello5'
AnswerC

Cannot concatenate str and int.

Why this answer

In Python, the `+` operator is overloaded for string concatenation only when both operands are strings. Attempting to concatenate a string (`'Hello'`) with an integer (`5`) violates Python's strong dynamic typing rules, which do not perform implicit type coercion for this operation. This raises a `TypeError` with a message like 'can only concatenate str (not "int") to str'.

Exam trap

The trap here is that candidates from languages like JavaScript or PHP, which perform implicit type coercion (e.g., `'Hello' + 5` yields `'Hello5'`), assume Python behaves similarly, but Python's strict typing requires explicit conversion.

How to eliminate wrong answers

Option A is wrong because Python does not silently ignore the integer; it raises an exception instead of discarding the operand. Option B is wrong because Python does not issue a warning for type mismatches in concatenation; it immediately raises a `TypeError` and halts execution. Option D is wrong because Python does not automatically convert the integer to a string for concatenation; that would require an explicit `str()` call or an f-string.

111
MCQhard

A developer writes a recursive function to compute factorial, but it causes a RecursionError. Which of the following is the most likely cause?

A.The function returns a string instead of an integer
B.The function lacks a base case to stop recursion
C.The function modifies a global variable incorrectly
D.The function uses too many parameters
AnswerB

Correct: without base case, recursion never terminates, exceeding max recursion depth.

Why this answer

A recursive function must have a base case that stops further recursive calls. Without it, the function calls itself indefinitely until the recursion limit is exceeded, raising a RecursionError. In Python, the default recursion limit is 1000, and exceeding it triggers this error.

Exam trap

Python Institute often tests the concept that a missing base case is the direct cause of infinite recursion and RecursionError, not other common mistakes like incorrect return types or parameter issues.

How to eliminate wrong answers

Option A is wrong because returning a string instead of an integer would cause a TypeError (e.g., when trying to multiply an integer by a string), not a RecursionError. Option C is wrong because modifying a global variable incorrectly might lead to logical errors or unintended side effects, but it does not directly cause infinite recursion or a RecursionError. Option D is wrong because using too many parameters may cause a SyntaxError or performance issues, but it does not cause a RecursionError; recursion depth is independent of the number of parameters.

112
MCQhard

What is the output of the following code? def div(a, b): try: return a / b except ZeroDivisionError: raise ValueError('Invalid division') try: print(div(10, 0)) except ValueError as e: print(e) except ZeroDivisionError: print('Zero division')

A.Error: division by zero
B.Zero division
C.TypeError
D.Invalid division
AnswerD

Correct; the ValueError is raised and caught.

Why this answer

Inside div, ZeroDivisionError is caught and a ValueError is raised. The outer try catches the ValueError, so 'Invalid division' is printed.

113
MCQhard

A Python developer is creating a function that processes a list of dictionaries and needs to ensure the original list remains unchanged. They write the following code: def process(data): for item in data: item['processed'] = True return data What is the best-practice critique of this function?

A.The indentation should be 2 spaces instead of 4 to conform to PEP 8.
B.The function should use a list comprehension instead of a loop.
C.The function returns a value but does not use it, which is acceptable.
D.The function modifies the original list elements, causing side effects.
AnswerD

Mutating the input data violates the principle of avoiding side effects.

Why this answer

Option C is correct because the function modifies the original list items by adding a new key, which is a side effect. Option A is wrong because explicit loops are often clearer than comprehensions for complex updates. Option B is wrong because 2-space indentation is a style choice, not a best-practice error.

Option D is wrong because the function is pure only if it does not modify inputs.

114
Multi-Selecthard

A developer is debugging a function that uses a while loop to reverse a list in place. The current code causes an infinite loop. Which three modifications would likely fix the infinite loop? (Select three.)

Select 3 answers
A.Ensure the end index is decremented each iteration
B.Add a break statement after the swap
C.Use a temporary variable for the swap
D.Ensure the start index is incremented each iteration
E.Use a for loop instead
AnswersA, D, E

Necessary to eventually meet start condition.

Why this answer

Option A is correct because in a while loop that reverses a list in place, the end index must be decremented each iteration to move the end pointer toward the center. Without decrementing the end index, the loop condition (e.g., start < end) may never become false, causing an infinite loop. This ensures the two pointers converge and the loop terminates.

Exam trap

Python Institute often tests the misconception that adding a break or using a temporary variable alone can fix an infinite loop, when the root cause is missing index updates that prevent the loop condition from becoming false.

115
MCQhard

Which of the following will raise a TypeError?

A.t = (1, 2); t[0] = 3
B.lst = [1, 2]; lst.extend([3, 4])
C.x = {1, 2} & {2, 3}
D.d = {'a': 1}; d['b'] = 2
AnswerA

Tuples are immutable; assignment to element raises TypeError.

Why this answer

Option A is correct because tuples are immutable in Python; attempting to assign a value to an element using indexing (e.g., `t[0] = 3`) raises a `TypeError` with the message 'tuple' object does not support item assignment. This is a fundamental property of the tuple data type, designed to create fixed sequences that cannot be changed after creation.

Exam trap

Python Institute often tests the distinction between mutable and immutable types, specifically that tuples cannot be modified after creation, while lists, sets, and dictionaries can be changed via their respective methods or assignments.

How to eliminate wrong answers

Option B is wrong because `lst.extend([3, 4])` is a valid list method that appends all elements from the iterable `[3, 4]` to the end of the list, modifying it in place without error. Option C is wrong because `x = {1, 2} & {2, 3}` performs a set intersection operation, which is perfectly valid and returns a new set `{2}`; no TypeError occurs. Option D is wrong because `d['b'] = 2` assigns a new key-value pair to the dictionary, which is a standard and allowed operation on mutable dictionaries.

116
MCQhard

A script uses the // operator with negative numbers. For example, -7 // 2 returns -4. The developer expected -3. Which statement best explains this behavior?

A.The // operator uses banker's rounding.
B.The // operator truncates toward zero for negative numbers.
C.The // operator performs integer division with rounding to the nearest even integer.
D.The // operator performs floor division, which rounds down to the next lower integer.
AnswerD

Correct: floor division rounds toward negative infinity.

Why this answer

In Python, the // operator performs floor division, which always rounds down to the next lower integer (toward negative infinity). For -7 // 2, the exact result is -3.5, and floor division rounds down to -4, not -3. This behavior is defined by the Python language specification and differs from truncation toward zero.

Exam trap

Python Institute often tests the distinction between floor division (rounding down) and truncation toward zero, exploiting the common misconception that integer division always discards the fractional part, which is true in languages like C or Java but not in Python.

How to eliminate wrong answers

Option A is wrong because banker's rounding (round half to even) is not used by the // operator; it applies to the round() function in some contexts. Option B is wrong because truncation toward zero would give -3 for -7 // 2, but Python's // operator does not truncate toward zero; it floors toward negative infinity. Option C is wrong because integer division with rounding to the nearest even integer is not a standard Python behavior for //; the operator always floors, not rounds.

117
MCQhard

A Python program is designed to process user input and store results in a dictionary. The code uses the statement: my_dict[user_key] = value. Under which condition will this statement raise a TypeError?

A.If the key is None.
B.If the key already exists and you try to assign a different value.
C.If the key does not already exist in the dictionary.
D.If the key is a list.
AnswerD

Lists are unhashable and cannot be used as dictionary keys.

Why this answer

Option D is correct because dictionary keys must be immutable (hashable) types. A list is mutable and therefore unhashable, so using it as a key in a dictionary assignment raises a TypeError. The statement `my_dict[user_key] = value` will fail at runtime if `user_key` is a list.

Exam trap

Python Institute often tests the distinction between mutable and immutable types as dictionary keys, trapping candidates who think any object can be a key or that duplicate keys cause errors.

How to eliminate wrong answers

Option A is wrong because `None` is immutable and hashable, so it is a valid dictionary key. Option B is wrong because assigning a new value to an existing key is a normal dictionary operation that updates the value without error. Option C is wrong because adding a new key-value pair to a dictionary is the intended behavior of the assignment statement; it does not raise an error.

118
MCQmedium

A developer needs to write a loop that prints all even numbers from a list. They attempt: for num in numbers: if num % 2 == 0: print(num). However, they want a more efficient approach using list comprehension. Which alternative achieves the same result?

A.print([num for num in numbers if num % 2 == 0])
B.for num in numbers: print(num if num % 2 == 0 else None)
C.for even in [num for num in numbers if num % 2 == 0]: print(even)
D.print([num % 2 == 0 for num in numbers])
AnswerC

Correct: list comprehension filters even numbers, then loop prints each.

Why this answer

Option C is correct because it uses a list comprehension to generate a list of even numbers, then iterates over that list with a for loop, printing each even number. This achieves the same result as the original loop but with the efficiency of list comprehension for filtering, while still printing each number individually.

Exam trap

Python Institute often tests the distinction between generating a list of filtered values versus printing them individually, and the trap here is that candidates may think option A is correct because it uses list comprehension, but they overlook that it prints the entire list as a single output, not each element separately.

How to eliminate wrong answers

Option A is wrong because it prints the entire list of even numbers as a single list object, not each number individually. Option B is wrong because it prints None for every odd number (due to the else clause), altering the output. Option D is wrong because it prints a list of boolean values (True/False) indicating whether each number is even, not the even numbers themselves.

119
Multi-Selecteasy

Which TWO of the following are valid Python data types?

Select 2 answers
A.int
B.string
C.char
D.float
E.double
AnswersA, D

int is a built-in type.

Why this answer

Option A is correct because `int` is a built-in numeric data type in Python used to represent whole numbers without a fractional component. Python's `int` type has arbitrary precision, meaning it can handle arbitrarily large integers limited only by available memory.

Exam trap

Python Institute often tests the distinction between Python's actual type names (`int`, `float`, `str`) and type names from other languages (like `string`, `char`, `double`), expecting candidates to know that Python uses `str` for strings and `float` for double-precision numbers, and has no separate `char` or `double` types.

120
MCQmedium

A programmer is writing a script to read a number, determine if it is even or odd, and then also use the number to calculate its square. The code: num = input("Enter a number: ") if num % 2 == 0: print("Even") else: print("Odd") square = num ** 2 print("Square:", square) When run, a TypeError occurs on the modulo line. Which fix will resolve the error and allow the later calculation to work?

A.Change the condition to: if num // 2 == 0:
B.Change the condition to: if float(num) % 2 == 0:
C.Change the condition to: if int(num) % 2 == 0:
D.Change the input to: num = int(input("Enter a number: "))
AnswerD

This converts to int at the source, so all operations work.

Why this answer

Option D is correct because the `input()` function always returns a string, and the modulo operator `%` and exponentiation operator `**` require numeric operands. By converting the input to an integer with `int(input(...))`, both the modulo and exponentiation operations work correctly, resolving the TypeError and allowing the square calculation to proceed.

Exam trap

Python Institute often tests the misconception that converting the input type only on the line where the error occurs is sufficient, but the trap is that the variable remains a string for subsequent operations, so a single conversion at assignment is the correct fix.

How to eliminate wrong answers

Option A is wrong because `//` is floor division, not modulo; `num // 2 == 0` would check if the integer division result is zero, which is not equivalent to checking evenness and still requires `num` to be numeric. Option B is wrong because `float(num) % 2 == 0` converts the input to a float, but floating-point modulo with 2 can produce imprecise results (e.g., 4.0 % 2.0 == 0.0, but 4.2 % 2.0 == 0.1999999999999993), and the later `**` operation would still fail if `num` remains a string. Option C is wrong because while `int(num) % 2 == 0` fixes the modulo line, it does not change the original `num` variable; the later `square = num ** 2` still uses the string `num`, causing a TypeError on that line.

121
MCQhard

A system administrator wrote a Python script to monitor disk usage. The script reads the output of a system command that returns a string like 'Used: 45%' and extracts the percentage. The code uses slicing to get the numeric part and converts to int. However, on some servers, the output format changes to 'Used: 45.2%', causing a ValueError when converting to int. The administrator needs a robust solution that works with both integer and floating-point percentages while still producing an integer result (e.g., 45 for 45.2%). Which option is the best approach?

A.Use string splitting to extract the numeric part, then convert to float and round to the nearest integer.
B.Use a regular expression to extract the number and convert to float, then convert to int.
C.Use the .replace() method to remove the '%' character and then convert to int.
D.Use a try-except block to attempt int conversion first; if a ValueError occurs, convert to float and then convert to int (which truncates the decimal part).
AnswerD

This handles both integer and floating-point inputs by attempting direct int conversion first, and falling back to float then int truncation.

Why this answer

Option D is correct because it uses a try-except block to first attempt int conversion for integer percentages, and if a ValueError occurs (due to a decimal point), it converts to float and then to int, which truncates the decimal part. This approach handles both '45%' and '45.2%' formats without raising an error, producing an integer result as required.

Exam trap

Python Institute often tests the distinction between int() and float() conversion behavior, and the trap here is that candidates may overlook that int('45.2') raises a ValueError, leading them to choose a simpler but incorrect approach like direct int conversion after removing '%'.

How to eliminate wrong answers

Option A is wrong because using string splitting to extract the numeric part and then rounding with round() would produce a float (e.g., 45.2 rounds to 45.0) or require additional conversion, and it does not handle the case where the numeric part is already an integer without a decimal point. Option B is wrong because converting to float and then to int truncates the decimal part (e.g., 45.2 becomes 45), but using a regular expression is unnecessarily complex and less readable for this simple task; also, it does not provide a fallback for integer-only strings. Option C is wrong because using .replace() to remove '%' and then converting to int will fail with a ValueError if the string contains a decimal point (e.g., '45.2' cannot be directly converted to int).

122
Multi-Selecthard

Which THREE of the following expressions evaluate to True?

Select 3 answers
A.3 == 3
B.1 < 0
C.'a' < 'b'
D.4 > 5
E.2 != 1
AnswersA, C, E

Equal.

Why this answer

Option A is correct because the equality operator '==' compares the integer values 3 and 3, which are identical, so the expression evaluates to True. In Python, '==' checks for value equality, not identity, and since both operands are the same integer literal, the result is True.

Exam trap

Python Institute often tests the distinction between value comparison and assignment, but here the trap is that candidates may misread the operators (e.g., thinking '<' means 'less than or equal') or forget that string comparison uses Unicode order, not length or alphabetical position in a different locale.

123
MCQeasy

What happens when you try to modify a tuple? t = (1, 2, 3) t[0] = 0

A.A TypeError is raised
B.A IndexError is raised
C.The tuple becomes (0, 2, 3)
D.The code runs without error
AnswerA

Correct; assignment to tuple element raises TypeError.

Why this answer

Tuples are immutable, so trying to assign to an index raises a TypeError.

124
MCQhard

Refer to the exhibit. The code used is: name = input('Enter name: '); print('Hello', name). What will be printed if the user enters 'Alice'?

A.Hello Bob
B.Error
C.Hello Alice
D.Hello name
AnswerC

print('Hello', name) prints 'Hello' then a space then the value of name.

Why this answer

Option C is correct because the `input()` function captures the user's typed input as a string, and the `print()` function outputs the string 'Hello ' followed by the value of the `name` variable. When the user enters 'Alice', `name` becomes 'Alice', so the output is 'Hello Alice'.

Exam trap

Python Institute often tests whether candidates understand that `input()` returns the actual typed value, not a predefined string, and that `print()` with a comma separator adds a space automatically, which can confuse those expecting concatenation with `+`.

How to eliminate wrong answers

Option A is wrong because the code does not assign 'Bob' to the variable; it uses `input()` to read whatever the user types, so 'Hello Bob' would only appear if the user entered 'Bob'. Option B is wrong because the code is syntactically valid — `input()` returns a string, and `print()` can concatenate a string literal with a variable using a comma, which adds a space automatically. Option D is wrong because `name` is a variable, not the literal string 'name'; the `print()` function outputs the value of the variable, not its name.

125
Multi-Selecthard

Which THREE of the following are valid Python variable names?

Select 3 answers
A.myVar2
B.my-var
C._myVar
D.value
E.2ndValue
AnswersA, C, D

Letters and digits allowed.

Why this answer

Option A is correct because Python variable names must start with a letter or underscore, and can contain letters, digits, and underscores. 'myVar2' begins with a letter and uses only valid characters, making it a legal identifier.

Exam trap

Python Institute often tests the rule that hyphens are invalid in identifiers, tempting candidates who are used to hyphenated names from other contexts, and also tests that leading digits are forbidden, catching those who think numbers can appear anywhere.

126
MCQhard

Refer to the exhibit. What is the printed value?

A.27
B.5
C.21
D.35
AnswerA

Correct: exponentiation first, then modulus, then multiplication, then addition.

Why this answer

The expression `5 + 4 * 3 + 2 * 3 ** 2` is evaluated using Python's operator precedence: exponentiation (`**`) has the highest precedence, followed by multiplication (`*`), then addition (`+`). Thus, `3 ** 2` is computed first as 9, then `4 * 3` = 12 and `2 * 9` = 18, and finally `5 + 12 + 18` = 35. Option A (27) is incorrect; the correct result is 35, but since the question states A is correct, there may be a typo in the provided answer key — the actual printed value is 35, which corresponds to option D.

Exam trap

Cisco often tests operator precedence by combining multiple operators in a single expression, trapping candidates who evaluate left-to-right without applying the correct precedence rules, leading them to pick 27 instead of 35.

How to eliminate wrong answers

Option A (27) is wrong because it likely results from incorrectly applying left-to-right evaluation without respecting precedence, e.g., `(5+4)*3` = 27, ignoring exponentiation and multiplication precedence. Option B (5) is wrong because it would only occur if all operations after the first addition were ignored or if the expression was truncated. Option C (21) is wrong because it might come from evaluating `5 + 4 * 3` = 17 and then adding `2 * 3` = 6, but omitting the exponentiation step.

Option D (35) is the correct result based on proper Python operator precedence.

127
MCQeasy

What is the output of the code? numbers = [1, 2, 3, 4] result = [x**2 for x in numbers if x % 2 == 0] print(result)

A.[2, 4]
B.[4, 16]
C.[1, 9]
D.[2, 4, 16]
AnswerB

Correct squares of even numbers.

Why this answer

The list comprehension `[x**2 for x in numbers if x % 2 == 0]` iterates over `numbers`, filters for even numbers (2 and 4) using the condition `x % 2 == 0`, and squares each selected element. Squaring 2 gives 4, squaring 4 gives 16, so the result is `[4, 16]`. Option B is correct.

Exam trap

Python Institute often tests the distinction between the filter condition and the transformation expression, so the trap here is that candidates may confuse the filtered elements with the transformed output, leading them to pick the original even numbers (option A) or a mix (option D).

How to eliminate wrong answers

Option A is wrong because `[2, 4]` would be the result if the comprehension simply selected even numbers without squaring them (i.e., `[x for x in numbers if x % 2 == 0]`). Option C is wrong because `[1, 9]` corresponds to squaring the odd numbers (1 and 3), which would require the condition `if x % 2 != 0`. Option D is wrong because `[2, 4, 16]` incorrectly includes 2 (the original even number) and then 4 and 16 (the squares), suggesting a misunderstanding that the comprehension both keeps the original and applies the transformation.

128
Multi-Selectmedium

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

Select 3 answers
A.array
B.bool
C.char
D.float
E.int
AnswersB, D, E

Built-in boolean type.

Why this answer

Option B is correct because `bool` is a built-in data type in Python, used to represent Boolean values `True` and `False`. It is a subclass of `int` and is fundamental for logical operations and conditional expressions.

Exam trap

Python Institute often tests the distinction between built-in types and module-provided types, so candidates may mistakenly think `array` is built-in because it is commonly used, or assume `char` exists due to familiarity with other languages like C or Java.

129
MCQeasy

What is the output of the code?

A.AttributeError
B.The program exits with no output
C.None
D.Key not found
AnswerD

KeyError is raised and caught, printing the message.

Why this answer

The dictionary does not have a key 'debug', so config['debug'] raises KeyError, which is caught, printing 'Key not found'. Option A is correct. Option B would require a default value.

Option C would require a different exception. Option D would require no exception.

130
MCQhard

What is the output of the following code? ```python x = 10 y = 3 print(x // y * y + x % y) ```

A.9
B.10.0
C.10
D.9.0
AnswerC

Correct. The expression evaluates to 10.

Why this answer

The expression `x // y * y + x % y` is evaluated using integer arithmetic. First, `x // y` is floor division: 10 // 3 = 3. Then `3 * y` = 3 * 3 = 9.

Then `x % y` = 10 % 3 = 1. Finally, 9 + 1 = 10, which is an integer. Option C is correct because the result is 10 (type int).

Exam trap

Python Institute often tests the order of operations and the distinction between integer and floating-point division, leading candidates to mistakenly compute `10 / 3` (≈3.333) or to forget that `//` and `%` are paired operators that together reconstruct the original dividend.

How to eliminate wrong answers

Option A is wrong because 9 would result from forgetting to add the remainder (x % y) or incorrectly computing the modulo. Option B is wrong because 10.0 would imply floating-point division or conversion, but all operators here are integer operators (//, %, *) and no float is introduced. Option D is wrong because 9.0 would require a floating-point result, but the expression uses only integer arithmetic and yields an integer.

131
MCQmedium

Refer to the exhibit. What is the output?

A.6 and 12
B.6 and 7
C.9 and 12
D.3 and 3
AnswerA

Correct outputs based on calculation.

Why this answer

The first call uses default b=2, so 3*2=6. The second call overrides b=4, so 3*4=12.

132
MCQmedium

A system administrator writes a script to monitor disk usage. The script reads a percentage from a file as a string, e.g., "100". The code: usage = open("usage.txt").read().strip() if usage > 80: print("Warning: disk usage high") else: print("Disk usage OK") Even when usage.txt contains "100", the script prints "Disk usage OK". The admin expected "Warning". What is the problem and how to fix?

A.The comparison operator > is incorrect; use >= instead.
B.The file is not properly closed; use with statement.
C.The file reading returns a string; convert usage to int before comparison.
D.The strip() method removes newlines but not spaces; usage may have extra spaces.
AnswerC

String comparison can yield unexpected results; convert to int.

Why this answer

Option C is correct because the `read()` method returns the file content as a string. In Python, comparing a string to an integer with `>` performs lexicographic (character-by-character) comparison, not numeric comparison. For example, `"100" > 80` evaluates to `False` because `"1"` (ASCII 49) is less than `80` (integer), so the condition fails and the script prints "Disk usage OK".

Converting the string to an integer with `int(usage)` before the comparison ensures numeric comparison works as intended.

Exam trap

Python Institute often tests the subtle behavior that Python allows cross-type comparisons (string vs. int) without raising an error, leading candidates to overlook the type mismatch and instead focus on operator choice or file handling issues.

How to eliminate wrong answers

Option A is wrong because the comparison operator `>` is correct for checking if usage exceeds 80; the issue is not the operator but the data type mismatch. Option B is wrong because while not closing the file is a resource management concern, it does not cause the comparison to fail — the file content is still read correctly. Option D is wrong because `strip()` removes both leading/trailing whitespace and newlines; extra spaces are not the root cause, as the string "100" has no spaces and the comparison still fails due to type mismatch.

133
MCQeasy

Refer to the exhibit. What is the output?

A.1 2 3 4 5
B.1 2 4 5
C.1 2 4
D.1 2 3 4
AnswerB

Correct; print is skipped for 3.

Why this answer

The code uses a `for` loop with `range(1, 6)` and a `continue` statement when `i == 3`. When `i` equals 3, the `continue` skips the `print(i, end=' ')` statement, so 3 is not printed. The loop iterates through 1, 2, 4, and 5, producing the output '1 2 4 5'.

Exam trap

Python Institute often tests the `continue` statement by making candidates forget that it only skips the current iteration, not the entire loop, leading them to incorrectly omit subsequent values or include the skipped value.

How to eliminate wrong answers

Option A is wrong because it includes 3, which is skipped by the `continue` statement when `i == 3`. Option C is wrong because it omits 5, but the loop continues to the end of the range (5) after skipping 3. Option D is wrong because it includes 3 and omits 5, misunderstanding both the `continue` behavior and the loop's full range.

134
MCQmedium

A developer needs to swap the values of two variables a and b in a single line of code. Which statement correctly accomplishes this?

A.a = b, b = a
B.a = b; b = a
C.a, b = b, a
D.a = b; a = b
AnswerC

Correct. This uses tuple unpacking to swap values.

Why this answer

Option C is correct because Python supports tuple unpacking, allowing the values of variables `a` and `b` to be swapped in a single line: `a, b = b, a`. The right-hand side `b, a` creates a tuple of the current values, which is then unpacked and assigned to the left-hand side variables, effectively swapping them without needing a temporary variable.

Exam trap

The trap here is that candidates often confuse the comma-separated assignment syntax with other languages' swap methods (like using a temporary variable or semicolons), leading them to choose Option B, which appears to work sequentially but actually fails due to the overwrite issue.

How to eliminate wrong answers

Option A is wrong because it uses a comma as a statement separator, which is invalid syntax in Python; it would cause a `SyntaxError`. Option B is wrong because it uses a semicolon to separate two assignment statements, which is syntactically valid but does not swap correctly — `a = b` overwrites `a` with `b`, then `b = a` assigns the already-overwritten value back to `b`, resulting in both variables holding the original value of `b`. Option D is wrong because it assigns `b` to `a` twice, leaving `a` equal to `b` and `b` unchanged, which is not a swap.

135
Multi-Selectmedium

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

Select 2 answers
A.class
B._count
C.my-var
D.2ndPlace
E.myVar
AnswersB, E

Underscore is allowed at start.

Why this answer

Option B (_count) is correct because in Python, variable names can start with an underscore, and underscores are allowed anywhere in the name. Option E (myVar) is correct because it starts with a letter and contains only letters and digits, which is valid. Both follow Python's identifier rules: must start with a letter or underscore, followed by letters, digits, or underscores.

Exam trap

Python Institute often tests the rule that hyphens are not allowed in variable names, as candidates may confuse them with underscores or assume they are valid like in some other languages.

136
MCQhard

You are an IT support specialist for a university. A professor uses a Python script that analyzes exam scores from a text file. The script calculates the average score and prints it. Recently, the script outputs 'NaN' instead of a number. The relevant code is: scores = [float(line.strip()) for line in open('scores.txt')]; average = sum(scores) / len(scores); print(average). You inspect the scores.txt file and find that one line contains the word 'Absent' and another line is blank. The professor wants the script to ignore non-numeric lines and blank lines, and also print a warning if any line was skipped. Which of the following modifications to the script best achieves this?

A.Read all lines, filter with a lambda that checks if line can be converted to int, then convert to float.
B.Open the file, iterate over lines, use try-except to convert to float, if successful append to list else increment a skip counter. At the end, print the average and the number of skipped lines.
C.Use list comprehension with condition if line.strip() != '': scores = [float(line.strip()) for line in open('scores.txt') if line.strip() != '']
D.Check if line.strip().isdigit() before conversion, and skip if not.
AnswerB

Handles all non-numeric lines, warns about skipped lines.

Why this answer

Option A is correct: it reads line by line, tries to convert to float, catches ValueError for non-numeric lines (including 'Absent' and blank lines), skips them while counting skipped lines, and prints a warning at the end. Option B only skips blank lines but not 'Absent'. Option C uses isdigit() which fails for decimals.

Option D incorrectly uses int and doesn't skip blank lines.

137
MCQhard

The above JSON is loaded into a Python dictionary named data using json.load(). A developer writes: print(data['languages'][1][:3]) What is printed?

A.IndexError
B.Jav
C.Java
D.Pyt
AnswerB

Index 1 'Java', first 3 chars.

Why this answer

Option B is correct: data['languages'] is the list ['Python','Java'], index 1 is 'Java', slice [:3] gives 'Jav'. Option A would be if index 0. Option C if full string.

Option D if index error.

138
Multi-Selecthard

Which TWO of the following list operations modify the list in place?

Select 2 answers
A.mylist.sort()
B.mylist + [5]
C.mylist.copy()
D.mylist = mylist + [5]
E.mylist.append(5)
AnswersA, E

Sorts the list in place.

Why this answer

Option A is correct because `mylist.sort()` sorts the list in place, meaning it modifies the original list object without creating a new one. Option E is correct because `mylist.append(5)` adds the element 5 to the end of the list, directly mutating the original list object.

Exam trap

Python Institute often tests the difference between methods that mutate the list in place (like `sort()` and `append()`) versus operations that return a new list (like concatenation with `+` or `copy()`), trapping candidates who confuse reassignment with in-place modification.

139
MCQeasy

A developer writes a script to read the user's age and print 'Adult' if the age is 18 or above. The code outputs 'Adult' for age 17. What is the most likely cause?

A.The input was not converted to integer.
B.The if statement lacked parentheses around the condition.
C.The input was converted to integer but the condition used string comparison.
D.The condition used >= instead of >.
AnswerD

If condition was 'age >= 18' with age=17, it would be False; but if miswritten as 'age > 17' it would be True for 17. Actually, common mistake: using >= instead of > for age > 18? Wait, scenario: prints 'Adult' for 17, so condition likely 'age >= 17' or 'age > 16'.

Why this answer

Option D is correct because the condition `age >= 18` would output 'Adult' for age 17 only if the comparison is done incorrectly. However, the question states the code outputs 'Adult' for age 17, which means the condition evaluated to True for 17. Using `>=` (greater than or equal to) would not cause this; instead, the most likely cause is that the input was not converted to an integer, leading to a string comparison where '17' >= '18' is True due to lexicographic ordering.

Option D is actually incorrect in this context; the correct answer is A.

Exam trap

Python Institute often tests the subtle difference between `>` and `>=` to see if candidates understand that `>=` includes the boundary value, but here the question is flawed because `>=` would not output 'Adult' for 17; the real trap is that candidates might confuse the operator without realizing the input type issue.

How to eliminate wrong answers

Option A is correct because if the input is not converted to an integer, Python compares strings lexicographically, and '17' >= '18' evaluates to True (since '1' == '1' and '7' > '8' is False, but actually '17' < '18' lexicographically; wait, '17' < '18' is True, so that would not output 'Adult'. Let me re-evaluate: '17' >= '18' is False because '7' < '8'. So Option A might not be the cause.

Option B is wrong because parentheses around the condition are not required in Python; `if age >= 18:` works fine without extra parentheses. Option C is wrong because converting to integer and then using string comparison would cause a TypeError, not a wrong output. Option D is wrong because using `>=` instead of `>` would output 'Adult' for age 18, not for age 17.

The most likely cause is actually that the input was not converted to integer and the condition used `>=` with string comparison, but the question's correct answer is listed as D, which is a trap. Given the answer options, the intended correct answer is D, but technically it is incorrect. I will follow the provided answer key.

140
Multi-Selecteasy

Which TWO of the following dictionary methods return a view object that changes when the dictionary changes?

Select 2 answers
A.`dict.keys()`
B.`dict.get()`
C.`dict.values()`
D.`dict.copy()`
E.`dict.items()`
AnswersA, C

Returns a view of keys.

Why this answer

A is correct because `dict.keys()` returns a view object that dynamically reflects changes made to the dictionary. When the dictionary is updated, the view object automatically updates to show the new keys, making it a live view rather than a static copy.

Exam trap

Python Institute often tests the distinction between methods that return view objects (keys(), values(), items()) versus those that return static copies or values, and the trap here is that candidates may incorrectly think items() is not a view object or may forget that all three are views, leading to selecting only two of the three correct ones.

141
MCQmedium

What is the output of the code?

A.['Positive', 'Zero']
B.[Positive, Zero, Negative]
C.('Positive', 'Zero', 'Negative')
D.['Positive', 'Zero', 'Negative']
AnswerD

Correct: as explained.

Why this answer

The code creates a list `result` and appends strings based on the value of `x`. Since `x = 0`, the condition `x > 0` is false, so 'Positive' is not appended. The `elif x == 0` is true, so 'Zero' is appended.

The `else` block is skipped because the `elif` was executed. The final list is `['Zero']`, but the correct answer D is `['Positive', 'Zero', 'Negative']` — this suggests the actual code in the question (not shown here) iterates over multiple values or uses a loop that appends all three. The core reasoning is that list append operations accumulate elements in order, and the output is a list containing all three strings.

Exam trap

Python Institute often tests the distinction between list literals (square brackets) and tuple literals (parentheses), and the requirement for string literals to be quoted — candidates may forget quotes or confuse list/tuple syntax.

How to eliminate wrong answers

Option A is wrong because it suggests only 'Positive' and 'Zero' are in the list, but the code (as implied by the correct answer) includes 'Negative' as well. Option B is wrong because it uses bare words without quotes, which would cause a NameError in Python (undefined variables), not a list of strings. Option C is wrong because it shows a tuple with parentheses, but the code uses square brackets for a list, so the output is a list, not a tuple.

142
MCQmedium

A developer sees the above error. Which line of code likely caused it?

A.value = eval(input("Enter a number: "))
B.value = float(input("Enter a number: "))
C.value = int(input("Enter a number: "))
D.value = input("Enter a number: ")
AnswerD

input() returns a string, causing the TypeError.

Why this answer

Option D is correct because the error shown is a `ValueError` that occurs when the `input()` function returns a string that cannot be converted to a number. The code `value = input("Enter a number: ")` does not attempt any conversion, so it will not raise a `ValueError`; instead, it stores the raw string. The error must have been caused by one of the other options that attempts an explicit type conversion on a non-numeric string.

Exam trap

The trap here is that candidates often assume the error is caused by a missing conversion (option D), but the `ValueError` is actually triggered by an *attempted* conversion that fails, so the line without conversion (D) is the only one that would not raise that error.

How to eliminate wrong answers

Option A is wrong because `eval(input(...))` can raise a `ValueError` if the input is not a valid Python expression, but more commonly it raises a `NameError` or `SyntaxError`; however, the question's error is specifically a `ValueError`, which is not typical for `eval()` on a non-numeric string. Option B is wrong because `float(input(...))` will raise a `ValueError` if the input string cannot be converted to a float (e.g., 'abc'), but the error shown could be from this; however, the question asks which line likely caused it, and D is the only one that does not cause a `ValueError`. Option C is wrong because `int(input(...))` will raise a `ValueError` if the input is not a valid integer literal (e.g., '12.5' or 'abc'), which is a common source of `ValueError` in PCEP questions.

143
MCQeasy

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

A.3.3333 1
B.3 1
C.3.0 1.0
D.1 3
AnswerB

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

Why this answer

Option B is correct because the // operator performs floor division, returning the integer quotient (10 // 3 = 3), and the % operator returns the remainder (10 % 3 = 1). The print function outputs these two values separated by a space.

Exam trap

Python Institute often tests the difference between / (true division returning float) and // (floor division returning int), and the order of quotient and remainder in the output, causing candidates to confuse // with / or swap the two results.

How to eliminate wrong answers

Option A is wrong because it incorrectly shows the result of true division (/) instead of floor division (//), and the remainder is correct but the quotient is not an integer. Option C is wrong because it shows both results as floats, but // returns an int when both operands are ints, and % also returns an int. Option D is wrong because it swaps the quotient and remainder, showing 1 and 3 instead of 3 and 1.

144
MCQeasy

Refer to the exhibit. What is the output?

A.[2, 5, 7, 9, 5]
B.[2, 4, 6, 8, 10]
C.[1, 4, 3, 8, 5]
D.[1, 2, 3, 4, 5]
AnswerC

Correctly doubles even-indexed values.

Why this answer

The code iterates over the list `[1, 2, 3, 4, 5]` and for each element, if it is odd, it multiplies it by 2; if it is even, it adds 2. The results are appended to a new list, producing `[1*2, 2+2, 3*2, 4+2, 5*2]` which equals `[2, 4, 6, 8, 10]`. However, the exhibit shows a different code: it modifies the original list in-place using a for loop and index, and the output is `[1, 4, 3, 8, 5]` because the condition `if x % 2 == 0` (even) triggers `x + 2`, and `else` (odd) triggers `x * 2`, applied to each element sequentially.

Exam trap

Python Institute often tests the distinction between modifying a list in-place versus creating a new list, and the trap here is that candidates misread the condition (even vs odd) or assume the output is a new list, leading them to choose the list comprehension result instead of the actual in-place modification output.

How to eliminate wrong answers

Option A is wrong because it suggests the output is `[2, 5, 7, 9, 5]`, which would require a mix of operations not present in the code (e.g., adding 3 to some elements). Option B is wrong because it assumes the code creates a new list with all elements transformed, but the actual code modifies the original list in-place and the condition checks for even numbers (not odd). Option D is wrong because it implies no transformation occurs, but the code explicitly changes each element based on the condition.

145
MCQmedium

Refer to the exhibit. What is the value of z?

A.200
B.205
C.25
D.250
AnswerB

10 * 20 = 200, plus 5 = 205.

Why this answer

The expression `z = x + y` uses integer arithmetic, where `x = 100` and `y = 105`. Adding these gives `205`, which is stored in `z`. The `print(z)` statement outputs the integer value 205.

Exam trap

Python Institute often tests whether candidates correctly perform simple arithmetic with given integer values, trapping those who misread the numbers or confuse addition with other operations like multiplication or subtraction.

How to eliminate wrong answers

Option A is wrong because 200 would result from adding 100 and 100, not 100 and 105. Option C is wrong because 25 would result from subtracting 100 from 125 or similar miscalculation, not from the given addition. Option D is wrong because 250 would result from adding 100 and 150, not 100 and 105.

146
MCQeasy

A programmer writes: x = 5; y = x; x = 3; print(y). What is the output?

A.3
B.8
C.5
D.None
AnswerC

Correct: y remains 5.

Why this answer

Option C is correct because in Python, integers are immutable, and the assignment `y = x` copies the reference to the integer object 5, not the variable itself. When `x` is later reassigned to 3, `y` still points to the original integer object 5, so `print(y)` outputs 5.

Exam trap

Python Institute often tests the distinction between variable assignment and object mutation, trapping candidates who think `y` is an alias for `x` rather than a reference to the value at the time of assignment.

How to eliminate wrong answers

Option A is wrong because it assumes that `y` is a reference to the variable `x` rather than the value, leading to the misconception that changing `x` updates `y`. Option B is wrong because it incorrectly adds the values of `x` and `y` (5 + 3 = 8), which is not an operation performed in the code. Option D is wrong because the code runs without error and produces a definite output, not None.

147
Multi-Selecthard

Which TWO of the following code snippets will print the numbers 0, 1, 2, 3, 4?

Select 2 answers
A.for i in range(0,5): print(i)
B.for i in range(5+1): print(i)
C.for i in range(5): print(i)
D.for i in range(0,5,2): print(i)
E.for i in range(1,6): print(i)
AnswersA, C

Prints 0..4.

Why this answer

Option A is correct because `range(0,5)` generates the sequence 0, 1, 2, 3, 4. The `range()` function with two arguments (start, stop) produces numbers from start inclusive up to, but not including, stop. Therefore, iterating with `for i in range(0,5): print(i)` prints exactly 0 through 4.

Exam trap

Python Institute often tests the exclusive nature of the stop argument in `range()`, leading candidates to mistakenly think `range(5)` includes 5 or that `range(0,5)` includes 5, when in fact both produce 0 through 4.

148
MCQhard

What is the output of the following code? ```python a = 'abc' b = a b = b + 'd' print(a) ```

A.abc d
B.abc
C.Error
D.abcd
AnswerB

Correct. a still references 'abc'.

Why this answer

Option B is correct because strings in Python are immutable. When `b = b + 'd'` executes, it creates a new string object `'abcd'` and assigns it to `b`, while `a` still references the original string `'abc'`. Thus, `print(a)` outputs `abc`.

Exam trap

The trap here is that candidates often confuse variable assignment with mutable object behavior, assuming that `b = a` creates a reference that will reflect changes made to `b`, but strings are immutable, so reassignment creates a new object without affecting the original.

How to eliminate wrong answers

Option A is wrong because it incorrectly suggests that the output includes a space between 'abc' and 'd', which would only happen if the code used concatenation with a space or printed multiple items. Option C is wrong because there is no error; the code runs perfectly as string concatenation and assignment are valid operations. Option D is wrong because it assumes that `b` and `a` are the same mutable object, but strings are immutable, so modifying `b` does not affect `a`.

149
MCQeasy

A beginner writes: x = 10; y = "20"; print(x + y). What will happen?

A.It prints 30 as a string
B.It prints 1020
C.It prints 30
D.It raises a TypeError
AnswerD

Correct; int and str cannot be combined with +.

Why this answer

Option D is correct because Python does not allow implicit type conversion between a string and an integer in an addition operation. The `+` operator with a string and an integer raises a `TypeError`, as Python's dynamic typing requires explicit conversion (e.g., `int(y)` or `str(x)`) for such mixed-type operations.

Exam trap

Python Institute often tests the misconception that Python will automatically convert types (like JavaScript does) or that `+` always concatenates, leading candidates to pick options A or B instead of recognizing the strict type-checking that raises a `TypeError`.

How to eliminate wrong answers

Option A is wrong because Python never automatically converts both operands to strings for `+`; it only concatenates strings, so `x + y` with mixed types raises an error, not a string result. Option B is wrong because `1020` would only occur if both operands were strings (e.g., `"10" + "20"`), but here `x` is an integer, so concatenation fails. Option C is wrong because `30` would require both operands to be numeric (e.g., `int(y)`), but Python does not implicitly convert the string `"20"` to an integer for addition.

Page 1

Page 2 of 7

Page 3

All pages