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

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

Page 2

Page 3 of 7

Page 4
151
MCQhard

A program evaluates the expression: (True or False) and not (True and False). What is the result?

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

Correct evaluation as described

Why this answer

Option D is correct because the expression `(True or False) and not (True and False)` evaluates step by step: `True or False` is `True`, `True and False` is `False`, `not False` is `True`, and finally `True and True` is `True`. In Python, boolean operators `or`, `and`, and `not` follow standard precedence (`not` highest, then `and`, then `or`), and the result is a boolean value.

Exam trap

Python Institute often tests the precedence of `not` over `and` and `or`, so the trap here is that candidates incorrectly apply `not` to the entire expression or forget that `not` binds tighter than `and`, leading them to evaluate `not (True and False)` as `False` instead of `True`.

How to eliminate wrong answers

Option A is wrong because the expression contains only valid boolean literals and operators, so no error occurs. Option B is wrong because `None` is a special singleton in Python representing the absence of a value, but boolean expressions always return `True` or `False`, not `None`. Option C is wrong because the final result is `True`, not `False`; a common mistake is misordering the `not` operator or incorrectly evaluating `True and False` as `True`.

152
Multi-Selecthard

Which TWO of the following expressions will evaluate to True?

Select 2 answers
A.3 is not 3
B.3 > 2 and 2 > 3
C.3 != 3.0
D.3 == 3.0
E.3 is 3
AnswersD, E

True, numeric comparison.

Why this answer

Option D is correct because in Python, the '==' operator compares values, and since integers and floats are compared by numeric value, 3 and 3.0 are numerically equal, so the expression evaluates to True. Option E is correct because 'is' checks object identity, and small integers like 3 are interned by Python, meaning they refer to the same object in memory, so '3 is 3' returns True.

Exam trap

Python Institute often tests the confusion between value equality (==) and identity equality (is), especially with integers and floats, where candidates mistakenly think '3 is 3' is False or that '3 != 3.0' is True due to type differences.

153
MCQeasy

A developer writes a script that prompts the user for their age and stores it in a variable. Which code snippet correctly converts the input to an integer?

A.age = int(input)
B.age = int(input("Enter age: "))
C.age = input("Enter age: ", int)
D.age = input(int("Enter age: "))
AnswerB

Correctly converts the input string to an integer.

Why this answer

Option B is correct because it uses the `int()` function to convert the string returned by `input()` into an integer. The `input()` function always returns a string, so wrapping it with `int()` performs the type conversion needed for numeric operations.

Exam trap

Python Institute often tests the distinction between a function reference (e.g., `input` without parentheses) and a function call (e.g., `input()`), leading candidates to mistakenly think `int(input)` is valid syntax.

How to eliminate wrong answers

Option A is wrong because `input` without parentheses is a reference to the function object, not a function call, so it does not prompt the user or return a value. Option C is wrong because `input()` does not accept a second argument; the prompt is the only parameter, and passing `int` as a second argument causes a TypeError. Option D is wrong because it attempts to call `int()` on a string before calling `input()`, which would raise a NameError since `"Enter age: "` is not a defined variable, and the parentheses are misplaced.

154
MCQeasy

A developer writes a function that calculates the area of a rectangle and prints the result inside the function. Later, they need to use this area in another calculation. What should they do to make the function reusable and composable?

A.Store the area in a global variable and access it later.
B.Modify the function to return the area instead of printing it.
C.Keep the function as is and call it from inside another function.
D.Pass the area to the next calculation using a print function argument.
AnswerB

Returning allows the result to be used in other calculations.

Why this answer

Option A is correct because returning the value allows the caller to use it in further computations. Option B is wrong because keeping the print inside prevents composition. Option C is wrong because using a global variable is poor practice and reduces reusability.

Option D is wrong because passing the result as a print argument doesn't change the logic.

155
MCQmedium

Which logical expression evaluates to True given that a = 5 and b = 10?

A.a > b and b < 0
B.not (a < b)
C.not (a > b)
D.a == b or not False
AnswerC

True because a>b false => not false = true.

Why this answer

Option C is correct because not (a > b) is True (since a > b is False). Option A is wrong because both are False. Option B is wrong because a < b is True, then not True is False.

Option D is wrong because a == b is False, and not False is True, but combined with or, it's True; however, the question expects a single expression, and C is simpler.

156
MCQhard

You are a developer for a financial application that processes transactions. The application uses a dictionary to store account balances where keys are account numbers (strings) and values are floats. A function `transfer(from_acc, to_acc, amount)` is supposed to subtract amount from `from_acc` and add it to `to_acc`. However, some transfers are resulting in incorrect balances: the `from_acc` balance is reduced but the `to_acc` balance is not increased. The code uses `try-except` to catch KeyError if an account does not exist. Upon inspection, the function first checks if both accounts exist, then performs subtraction, then addition, and finally returns success. No exceptions are raised during the problematic transfers. The accounts definitely exist. What is the most likely cause?

A.The dictionary is being modified concurrently by multiple threads or processes without synchronization, leading to race conditions.
B.The function catches KeyError and silently returns without completing the transfer.
C.The function does not check if the from_acc has sufficient balance before subtracting.
D.The balances are stored as strings instead of floats, causing concatenation instead of arithmetic.
AnswerA

Race condition can cause the second update to be lost.

Why this answer

Option A is correct because the described symptom — the `from_acc` balance is reduced but the `to_acc` balance is not increased — is a classic race condition. In Python, dictionary operations like `dict[key] -= amount` are not atomic; they involve a read, modify, and write sequence. If two threads execute the transfer function concurrently on overlapping accounts, one thread's write to `to_acc` can be overwritten by another thread's stale read, causing the addition to be lost.

The `try-except` only catches `KeyError`, not data races, and since no exception is raised, the only plausible explanation is unsynchronized concurrent access.

Exam trap

Python Institute often tests the misconception that Python's GIL prevents all concurrency issues, but the trap here is that the GIL does not make compound operations atomic, so race conditions can still occur with dictionary updates.

How to eliminate wrong answers

Option B is wrong because the problem states that no exceptions are raised during the problematic transfers, so the function is not silently returning due to a caught KeyError; the transfers proceed but produce incorrect balances. Option C is wrong because insufficient balance would cause a negative balance in `from_acc`, but the symptom is that `to_acc` is not increased — the subtraction from `from_acc` works correctly, so the issue is not about balance checking. Option D is wrong because if balances were stored as strings, the subtraction operation (`-=`) would raise a TypeError, not silently produce incorrect results; the problem states no exceptions occur, so the types must be correct.

157
MCQeasy

A beginner Python learner writes a script to swap two numbers: a = 10 b = 20 a = b b = a print("a =", a, "b =", b) The output is "a = 20 b = 20". The learner expected "a = 20 b = 10". Which of the following is the most Pythonic way to fix the code?

A.Use bitwise XOR: a ^= b; b ^= a; a ^= b
B.Use tuple unpacking: a, b = b, a
C.Use a temporary variable: temp = a; a = b; b = temp
D.Use integer arithmetic: a = a + b; b = a - b; a = a - b
AnswerB

This is the standard Pythonic swap.

Why this answer

Option B is correct because tuple unpacking is the most Pythonic and idiomatic way to swap two variables. It leverages Python's ability to evaluate the right-hand side as a tuple before assignment, so the original values of `a` and `b` are captured simultaneously, avoiding the overwrite issue in the original code.

Exam trap

Python Institute often tests the misconception that any working swap is equally Pythonic, but the PCEP emphasizes idiomatic Python (PEP 8 style), making tuple unpacking the only correct answer despite other options being functionally correct.

How to eliminate wrong answers

Option A is wrong because while bitwise XOR can swap integers, it is not Pythonic, less readable, and can fail with floating-point numbers or large integers due to Python's arbitrary precision. Option C is wrong because using a temporary variable is a valid but non-Pythonic approach; it works but is verbose and not the preferred style in Python. Option D is wrong because integer arithmetic can cause overflow in languages with fixed-width integers, but in Python it works; however, it is less readable and not idiomatic, making it non-Pythonic.

158
Multi-Selecteasy

Which TWO of the following are valid variable names in Python?

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

Valid: letters and underscore.

Why this answer

Options B and D are valid: underscores and letters allowed. Option A starts with digit. Option C contains a hyphen.

Option E is a reserved keyword.

159
MCQmedium

A program reverses a string using a while loop. The code is: text = "hello" reversed_text = "" index = len(text) - 1 while index > 0: reversed_text += text[index] index -= 1 print(reversed_text) It prints 'olle' instead of 'olleh'. What is the error?

A.Change the condition to 'while index >= 0:'
B.Change the initial index to len(text)
C.Use a for loop instead
D.Use string slicing: reversed_text = text[::-1]
AnswerA

This ensures index 0 is processed.

Why this answer

The while loop condition `index > 0` stops when `index` becomes 0, so the character at index 0 (the first character 'h') is never appended to `reversed_text`. Changing the condition to `while index >= 0:` ensures the loop runs for index values from 4 down to 0 inclusive, producing the full reversed string 'olleh'.

Exam trap

Python Institute often tests off-by-one errors in while loops, where candidates mistakenly think `index > 0` covers all elements because they forget that the first index is 0, not 1.

How to eliminate wrong answers

Option B is wrong because setting the initial index to `len(text)` would cause an IndexError on the first iteration (index 5 is out of range for a 5-character string). Option C is wrong because using a for loop is not necessary; the while loop logic is correct except for the off-by-one condition, so switching to a for loop does not fix the root cause. Option D is wrong because while string slicing `text[::-1]` is a valid alternative, the question asks for the error in the given while loop code, not for a different implementation.

160
MCQmedium

A weather station records temperature as a string '23.5'. The technician writes code to convert to Fahrenheit for a report. Which code will produce the correct Fahrenheit value without errors?

A.fahrenheit = float(celsius) * 9/5 + 32
B.fahrenheit = celsius * 9/5 + 32
C.fahrenheit = int(celsius) * 9/5 + 32
D.fahrenheit = (celsius + 32) * 9/5
AnswerA

Correctly converts to float and applies formula

Why this answer

Option A is correct because it explicitly converts the string '23.5' to a float using the `float()` function, preserving the decimal part. The expression `float(celsius) * 9/5 + 32` then correctly applies the Fahrenheit conversion formula (F = C * 9/5 + 32) using floating-point arithmetic, which yields the precise result 74.3 without any type errors.

Exam trap

Python Institute often tests the distinction between `int()` and `float()` conversion, trapping candidates who forget that `int()` truncates the decimal part, leading to a loss of precision in calculations.

How to eliminate wrong answers

Option B is wrong because `celsius` is a string ('23.5'), and multiplying a string by a number causes a TypeError in Python (e.g., `'23.5' * 9` is invalid). Option C is wrong because `int(celsius)` truncates the decimal part, converting '23.5' to 23, which produces an incorrect Fahrenheit value (73.4 instead of 74.3). Option D is wrong because it uses the wrong formula: adding 32 before multiplying by 9/5 gives (23.5 + 32) * 9/5 = 99.9, which is not the correct conversion from Celsius to Fahrenheit.

161
MCQeasy

How many times will the following loop print 'Hi'? for i in range(3): print('Hi')

A.2
B.3
C.0
D.4
AnswerB

Correct number of iterations.

Why this answer

The loop `for i in range(3):` iterates exactly three times because `range(3)` generates the sequence 0, 1, 2. Each iteration executes `print('Hi')`, so 'Hi' is printed three times. Option B is correct.

Exam trap

Python Institute often tests the off-by-one misconception where candidates think `range(3)` includes 3, leading them to choose 4 iterations, or they mistakenly count from 1 instead of 0.

How to eliminate wrong answers

Option A is wrong because it suggests the loop runs only twice, which would be the case for `range(2)` or a loop with a different stop value. Option C is wrong because the loop always executes at least once when the stop value is positive; `range(3)` is not empty. Option D is wrong because `range(3)` stops before 3, producing exactly three values, not four.

162
MCQeasy

Which operator is used for integer division in Python?

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

Correct; // performs floor division.

Why this answer

Option D is correct because the // operator in Python performs floor division, which returns the integer quotient after dividing two numbers, discarding any fractional remainder. For example, 7 // 2 yields 3, not 3.5, making it the explicit integer division operator.

Exam trap

Python Institute often tests the distinction between / (true division returning a float) and // (floor division returning an integer), trapping candidates who assume / always performs integer division in Python as it does in some other languages.

How to eliminate wrong answers

Option A is wrong because % is the modulo operator, which returns the remainder of a division, not the quotient. Option B is wrong because ** is the exponentiation operator, used for raising a number to a power. Option C is wrong because / is the true division operator, which always returns a float result even if the operands are integers.

163
Matchingmedium

Match each Python keyword to its use.

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

Concepts
Matches

Starts a conditional statement

Starts a loop over a sequence

Starts a loop that repeats while a condition is true

Defines a function

Exits a function and optionally returns a value

Why these pairings

These are reserved keywords in Python that control program flow and structure.

164
MCQhard

Refer to the exhibit. Which of the following is true about the output?

A.Prints "Error:" then "Done" without the message
B.Raises an unhandled exception
C.Prints "Error: invalid literal for int() with base 10: 'abc'" then "Done"
D.Prints only "Done"
AnswerC

The error message is printed, then finally runs.

Why this answer

int("abc") raises ValueError, which is caught, prints the error message from the exception, then the finally block executes. Option A is correct.

165
MCQeasy

A developer writes a function that should return the sum of two numbers, but the code returns 0 instead. What is the most likely cause? def add(a, b): result = a + b print(add(3, 4))

A.The function is not defined before the call.
B.The variable 'result' is not defined.
C.The function parameters are of incompatible types.
D.The function does not have a return statement.
AnswerD

The function computes the sum but does not return it, returning None instead.

Why this answer

Option D is correct because the function `add` computes `a + b` and assigns it to `result`, but lacks a `return` statement. In Python, a function without an explicit `return` automatically returns `None`. When `print(add(3, 4))` is executed, it prints `None`, not the sum.

The question states the code returns 0, which is a common misreading — the actual output is `None`, but the core issue is the missing `return`.

Exam trap

Python Institute often tests the distinction between computing a value inside a function and actually returning it — the trap here is that candidates see `result = a + b` and assume the sum is automatically output, missing the critical absence of the `return` statement.

How to eliminate wrong answers

Option A is wrong because the function is defined before the call (the definition appears on lines 1-2, and the call is on line 4). Option B is wrong because `result` is defined inside the function (line 2), so it exists in the local scope; the problem is that it is never returned. Option C is wrong because both parameters are integers (3 and 4), which are compatible types for the `+` operator; no TypeError would occur.

166
MCQeasy

Given a list of names = ['Alice', 'Bob', 'Charlie'], a developer wants to create a dictionary mapping each name to its length. Which expression accomplishes this?

A.{len(name): name for name in names}
B.{name: len(name) for name in names}
C.{name: len for name in names}
D.{name: length for name in names}
AnswerB

Correct: This comprehension creates the mapping with each name and its length.

Why this answer

Dictionary comprehension {name: len(name) for name in names} creates the desired mapping. Option C is correct. Option A is incorrect because len without parentheses returns the function object.

Option B swaps key and value. Option D uses an undefined variable 'length'.

167
Multi-Selectmedium

Which TWO of the following expressions evaluate to True?

Select 2 answers
A.3 == int("3")
B."3" == 3
C.bool(1)
D.bool(0)
E.3 == 3.0
AnswersA, E

int("3") returns 3, so True.

Why this answer

Option A is correct because the `int()` function converts the string `"3"` to the integer `3`, and the `==` operator compares the values, returning `True` since both sides are the integer `3`. Option E is correct because Python's `==` operator performs value equality, and `3` (integer) and `3.0` (float) represent the same numeric value, so the comparison evaluates to `True`.

Exam trap

Python Institute often tests the misconception that `==` performs type coercion for all types (like JavaScript), but in Python, `==` only coerces numeric types (int, float, complex) and returns `False` for cross-type comparisons like string vs int.

168
MCQmedium

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

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

Correct result.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

169
MCQeasy

Refer to the exhibit. What is the output?

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

Correct slice.

Why this answer

The code iterates over the list [1, 2, 3] using a for loop. The variable `i` takes each element in order. The loop appends `i` to the new list `result` only if `i` is not equal to 3.

Since 3 is the last element, it is skipped, so `result` becomes [1, 2]. The final print outputs [1, 2].

Exam trap

Python Institute often tests the distinction between iterating over list elements versus list indices, and the trap here is that candidates mistakenly think the loop variable represents an index (0, 1, 2) rather than the actual list values.

How to eliminate wrong answers

Option A is wrong because it includes 3, but the condition `if i != 3` explicitly excludes 3 from being appended. Option B is wrong because it suggests the loop starts at 0, but the list contains 1, 2, 3, not indices. Option D is wrong because it omits 1 and includes 3, but the loop appends 1 and 2, and skips 3.

170
Multi-Selecteasy

Which TWO of the following are valid ways to comment in Python?

Select 2 answers
A.$ This is a comment
B.# This is a comment
C./* This is a comment */
D.// This is a comment
E.''' This is a comment '''
AnswersB, E

Standard single-line comment.

Why this answer

Option B is correct because the hash symbol (#) is the standard syntax for single-line comments in Python. Everything after # on that line is ignored by the Python interpreter, making it a valid comment.

Exam trap

Python Institute often tests the distinction between Python's comment syntax and comment styles from other languages (e.g., //, /* */) to catch candidates who are familiar with C-family languages but new to Python.

171
Matchingmedium

Match each exception type to its description.

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

Concepts
Matches

Raised when a function receives an argument of correct type but inappropriate value

Raised when an operation is applied to an object of inappropriate type

Raised when a sequence subscript is out of range

Raised when a mapping key is not found in a dictionary

Raised when division or modulo operation is performed with zero as divisor

Why these pairings

These are built-in exceptions in Python that indicate specific error conditions.

172
MCQeasy

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

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

input() returns a string; string * 2 duplicates the string.

Why this answer

Option A is correct because input returns a string, and multiplying a string repeats it. Option B is wrong because there is no syntax error. Option C is wrong because the logic is correct if the input is numeric, but the type is wrong.

Option D is wrong because print does not cause this behavior.

173
Multi-Selecteasy

Which TWO of the following expressions produce the integer 5?

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

Floor division returns integer 5.

Why this answer

Option B, `10 // 2`, uses floor division in Python, which divides 10 by 2 and returns the integer quotient 5, discarding any fractional remainder. Option C, `int(5.7)`, truncates the decimal part of the float 5.7, converting it directly to the integer 5. Both expressions produce the exact integer value 5.

Exam trap

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

174
Multi-Selecteasy

Which TWO of the following are valid Python variable names?

Select 2 answers
A.my_var2
B.2nd_var
C._myvar
D.my-var
E.for
AnswersA, C

Letters, underscores, and digits are allowed.

Why this answer

Valid variable names can start with underscore or letter, and contain letters, digits, underscores. Keywords are not allowed.

175
Multi-Selecteasy

Which TWO of the following are valid ways to determine if a variable 'x' is an integer? (Select two.)

Select 2 answers
A.type(x) == int
B.x.isint()
C.x.__class__ == int
D.isinstance(x, int)
E.int(x) == x
AnswersA, D

Valid; compares type.

Why this answer

Option A is correct because the `type()` function returns the type of the object, and comparing it directly to `int` checks if the variable is exactly an integer. This is a straightforward and reliable way to test the type in Python.

Exam trap

Cisco often tests the distinction between type-checking methods and the misconception that `int(x) == x` is a valid type check, when in fact it only checks value equality after conversion and can produce false positives with floats or raise errors with non-numeric types.

176
Multi-Selecteasy

Which TWO of the following are valid variable names in Python?

Select 2 answers
A._myVar
B.myVar
C.my-var
D.my_var
E.2ndPlace
AnswersA, D

Underscore is allowed as first character, and name contains only letters/underscores.

Why this answer

Variable names must start with a letter or underscore, and cannot contain hyphens or start with a digit. '2ndPlace' starts with a digit, 'my-var' contains a hyphen. Valid ones are '_myVar' and 'my_var'.

177
MCQmedium

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

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

Correct: converts input to float.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

178
Multi-Selectmedium

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

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

True: 1 equals True.

Why this answer

Option A is correct because in Python, the boolean value `True` is equal to the integer `1` due to the fact that `bool` is a subclass of `int`, and `True` is internally represented as `1`. The comparison `1 == True` evaluates to `True` because Python performs implicit type coercion, converting `True` to `1` before the equality check.

Exam trap

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

179
MCQmedium

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

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

Uses default b=5.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

180
Multi-Selectmedium

Which TWO of the following are valid Python variable names?

Select 2 answers
A._name
B.2name
C.name$
D.name-2
E.name_2
AnswersA, E

Valid. Starts with underscore.

Why this answer

Option A is correct because Python variable names must start with a letter or an underscore, and '_name' begins with an underscore, which is allowed. The rest of the name consists of letters and underscores, making it a valid identifier per Python's naming rules.

Exam trap

Python Institute often tests the misconception that special characters like '$' or hyphens are allowed in variable names, or that names can start with digits, confusing Python's rules with those of other languages like JavaScript or shell scripting.

181
MCQmedium

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

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

Correct: Multiple return values without brackets form a tuple.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

182
MCQeasy

A junior developer needs to write code that processes a list of student scores and stops processing when a score of 100 is encountered, as that score represents a perfect score that should be treated separately. Which loop construct is most appropriate?

A.for score in scores: if score == 100: pass ...
B.for score in scores: if score == 100: break ... further processing
C.for i in range(len(scores)): if scores[i] == 100: exit() ...
D.while scores: score = scores.pop(); if score == 100: continue ...
AnswerB

Correct; break stops the loop.

Why this answer

Option B is correct because the `break` statement immediately exits the loop when a score of 100 is encountered, which matches the requirement to stop processing further scores. The `for` loop iterates over the list naturally, and the `if` condition checks for the perfect score, making this the most straightforward and efficient construct for this scenario.

Exam trap

Python Institute often tests the distinction between `break`, `continue`, and `pass` in loops, and the trap here is that candidates may confuse `continue` (which skips only the current iteration) with `break` (which exits the loop entirely), leading them to choose option D incorrectly.

How to eliminate wrong answers

Option A is wrong because `pass` is a no-op statement that does nothing; it would skip the 100 but continue processing subsequent scores, failing to stop the loop. Option C is wrong because `exit()` terminates the entire program, not just the loop, which is overly drastic and not appropriate for simply stopping score processing. Option D is wrong because `continue` skips the current iteration and moves to the next, but it does not stop the loop; also, using `pop()` modifies the list destructively, which is not required and can lead to unintended side effects.

183
MCQmedium

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

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

5 + 3 = 8.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

184
Drag & Dropmedium

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

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

Steps
Order

Why this order

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

185
MCQmedium

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

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

Correct: continue skips the current iteration for negative amounts.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

186
Multi-Selectmedium

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

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

Valid list comprehension.

Why this answer

Option A is correct because it uses a list comprehension that iterates over the tuple (10, 20, 30) and creates a new list with the same elements. This is a valid Python syntax for constructing a list from an iterable.

Exam trap

Python Institute often tests the distinction between the list() constructor requiring a single iterable argument versus multiple positional arguments, and the use of correct list literal syntax (commas vs. semicolons), to catch candidates who confuse Python with other languages like JavaScript or C.

187
MCQeasy

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

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

Exception handling allows the script to continue processing other rows.

Why this answer

Option B is correct: using a try-except block allows catching the specific error for each row and handling it (e.g., skipping or logging) while continuing the rest of the file. Option A is wrong because logging alone does not prevent the crash. Option C is wrong because replacing all values with numbers may corrupt data.

Option D is wrong because having the source fix the data is not always feasible and does not solve the immediate script issue.

188
MCQeasy

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

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

Returning a new list keeps the function pure and reusable.

Why this answer

Option C is correct: collect qualifying employees in a list and return it. Option A is wrong because appending to a global list is a side effect and bad practice. Option B is wrong because it modifies the original dictionary.

Option D is wrong because returning None is unhelpful.

189
Matchingmedium

Match each Python data type to its description.

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

Concepts
Matches

Whole numbers, e.g., 42

Numbers with decimal point, e.g., 3.14

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

Logical values True or False

Ordered, mutable collection of items

Why these pairings

These are the basic built-in data types in Python.

190
Matchingmedium

Match each Python function to its description.

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

Concepts
Matches

Outputs objects to the console

Reads a string from standard input

Returns the number of items in a container

Returns the type of an object

Converts a value to an integer

Why these pairings

These are built-in functions commonly used in Python programming.

191
MCQmedium

What is the output of the code in the exhibit?

A.Greater\nLess or equal
B.SyntaxError
C.Less or equal
D.Greater
AnswerD

Condition is true.

Why this answer

Option B is correct because x=10 is greater than 5, so the if branch executes, printing 'Greater'. Option A is wrong because the condition is true. Option C is wrong because both prints are not executed.

Option D is wrong because there is no syntax error.

192
MCQeasy

Which of the following expressions evaluates to False?

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

3 is not >= 4, so false.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

193
MCQmedium

A developer writes a function that returns multiple values as a tuple. Which of the following is a valid way to unpack the result into separate variables?

A.result = func(); a, b = result[0], result[1]
B.a, b, c = func()
C.a = func()[0]; b = func()[1]
D.a, b = func()
AnswerD

This is direct tuple unpacking.

Why this answer

Option D is correct because when a function returns multiple values as a tuple, Python allows tuple unpacking directly in an assignment statement. The syntax `a, b = func()` automatically unpacks the two-element tuple into the variables `a` and `b`, which is the standard and most Pythonic way to handle such a return.

Exam trap

Python Institute often tests the requirement that the number of variables on the left must exactly match the number of elements in the returned tuple, so candidates who choose option B fall into the trap of assuming extra variables are simply ignored or set to `None`.

How to eliminate wrong answers

Option A is wrong because while it technically works, it is unnecessarily verbose and not the standard unpacking syntax; it manually indexes the tuple, which defeats the purpose of Python's built-in unpacking feature. Option B is wrong because it attempts to unpack a two-element tuple into three variables, which will raise a `ValueError: too many values to unpack (expected 3)` at runtime. Option C is wrong because it calls `func()` twice, which is inefficient and may cause side effects if the function has state or performs I/O; additionally, it does not use tuple unpacking at all.

194
Multi-Selecthard

Which TWO operators in Python yield an integer result when applied to two integers?

Select 2 answers
A.//
B.**
C.%
D.*
E./
AnswersA, C

Floor division always returns an integer for ints.

Why this answer

The floor division operator (//) always returns an integer result when both operands are integers, discarding any fractional part. For example, 7 // 2 yields 3, not 3.5. This is because floor division performs integer division and truncates toward negative infinity, ensuring the result type is int when both inputs are int.

Exam trap

Python Institute often tests the distinction between / (always returns float) and // (returns int for int operands), and the trap here is that candidates mistakenly think the modulo operator (%) returns a float, but it actually returns an integer when both operands are integers, and they may also incorrectly believe that multiplication (*) always returns an integer (which it does, but the exam deliberately omits it from the correct answers to test knowledge of // and % specifically).

195
MCQeasy

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

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

Correct: the 'in' operator is concise and readable.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

196
MCQhard

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

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

Correct: the result is float.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

197
MCQeasy

Which of the following variable names is valid in Python?

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

Underscores are allowed and often used for private attributes.

Why this answer

Option C is correct because variable names can start with an underscore. Option A is wrong because it starts with a digit. Option B is wrong because 'my-var' contains a hyphen.

Option D is wrong because 'class' is a reserved keyword.

198
MCQeasy

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

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

Correct: input() returns a string

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

199
Multi-Selecteasy

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

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

Converts tuple to list.

Why this answer

Correct options are A, C, D. A uses square brackets with elements. C uses list() constructor on an iterable.

D uses list comprehension. B uses curly braces which creates a set, not list. E uses parentheses which creates a tuple.

200
MCQeasy

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

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

A trailing comma creates a singleton tuple.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

201
MCQmedium

You are working on a Python application that interacts with an external API to fetch user data. The API returns JSON responses. Occasionally, the API returns a response with a missing key that your code assumes always exists, causing a KeyError. The application is critical and must continue functioning even if some data is incomplete. The data is processed in a loop over a list of user IDs. Your team lead suggests using the dictionary's get() method with a default value. However, the nested structure may have missing keys at multiple levels. What is the most robust way to handle this?

A.Use .get() with defaults for every key access, including nested ones, to avoid exceptions.
B.Check for key existence using 'in' for every key before accessing.
C.Wrap the entire loop in a try-except that catches any exception and continues.
D.Use a try-except inside the loop to catch KeyError and other expected exceptions for each item.
AnswerD

Precise exception handling allows logging and skipping only problematic items.

Why this answer

Option D is correct: using a try-except block around the data extraction allows catching KeyError (or TypeError) and handling the error at the item level. Option A is wrong because using .get() only handles one level; nested missing keys still cause errors. Option B is wrong because checking for every key existence before access makes code verbose and still may miss some.

Option C is wrong because ignoring all exceptions might hide other unrelated errors.

202
MCQeasy

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

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

Tuples do not support item assignment.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

203
MCQhard

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

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

Accessing a missing key raises KeyError.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

204
MCQhard

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

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

Uppercase with underscores for constants.

Why this answer

Option D is correct because constants are typically named in uppercase with underscores. Option A is wrong because it uses camelCase which is not recommended for constants. Option B is wrong because it uses lowercase with spaces.

Option C is wrong because it starts with a number.

205
MCQmedium

What is the output of the code?

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

Division yields float.

Why this answer

The expression `3 / 2` performs true division in Python, which always returns a float even if both operands are integers. The result is `1.5`, and `type(1.5)` returns `<class 'float'>`. Therefore, option B is correct.

Exam trap

Python Institute often tests the distinction between true division (`/`) and floor division (`//`), and the trap here is that candidates mistakenly think dividing two integers always yields an integer, forgetting that Python 3's `/` always returns a float.

How to eliminate wrong answers

Option A is wrong because `3 / 2` does not produce a string; it produces a numeric value, and `type()` returns a class object, not a string literal. Option C is wrong because true division (`/`) never returns an int in Python 3; it always returns a float, even when the division is exact (e.g., `4 / 2` returns `2.0`). Option D is wrong because the result of `3 / 2` is not a Boolean; it is a numeric float, and `type()` would never return `<class 'bool'>` for a division operation.

206
MCQeasy

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

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

Division returns a float.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

207
MCQmedium

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

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

Correct: both conditions must be true.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

208
MCQeasy

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

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

Correct; 0 is falsy.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

209
MCQeasy

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

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

Correct calculation.

Why this answer

The exponentiation operator ** has higher precedence than multiplication, so radius**2 = 25, then 3.14*25 = 78.5. Option A is correct.

210
MCQeasy

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

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

Most straightforward.

Why this answer

Option C is correct because for loop with range(5) is ideal for a fixed number of iterations. Option A (while loop) works but requires manual increment and condition. Option B (do-while) doesn't exist in Python.

Option D (recursion) is overkill.

211
MCQhard

A server logs are stored as a list of tuples: `logs = [('2024-01-10', 'INFO', 'Started'), ('2024-01-10', 'ERROR', 'Disk full')]`. A developer wants to count how many ERROR logs exist. Which code snippet correctly counts them?

A.count = logs.count(('ERROR',))
B.count = sum(log[1] == 'ERROR' for log in logs)
C.count = [log for log in logs if log[1] == 'ERROR']
D.count = len(logs)
AnswerB

Sum of booleans gives the count.

Why this answer

Option B uses a generator expression with `sum()` to count how many tuples in the `logs` list have the second element equal to `'ERROR'`. The expression `log[1] == 'ERROR'` evaluates to `True` (which is treated as 1) or `False` (0) for each tuple, and `sum()` adds them up, giving the correct count of ERROR logs.

Exam trap

Python Institute often tests the distinction between `list.count()` (which requires an exact match of the entire element) and counting via a conditional expression with `sum()`, leading candidates to mistakenly think `count()` can filter by a partial tuple or a specific field.

How to eliminate wrong answers

Option A is wrong because `list.count()` counts exact matches of the provided argument; `logs.count(('ERROR',))` looks for a tuple containing only `'ERROR'`, but each log entry is a 3-element tuple, so no match is found and the count is always 0. Option C is wrong because it creates a list of matching tuples, not a count; it would require `len()` to get the number, and the question asks for a code snippet that counts, not just filters. Option D is wrong because `len(logs)` returns the total number of log entries (2), not the count of ERROR logs.

212
MCQhard

Which expression evaluates to False?

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

3 is not greater than 4, so False.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

213
Multi-Selecthard

Which THREE of the following statements about function arguments are true? (Select exactly 3)

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

Keyword arguments can be specified in any order after positional arguments.

Why this answer

Option A is true: default arguments are evaluated at function definition time. Option B is false: keyword arguments can be used in any order as long as they are after positional. Option C is true: *args collects extra positional arguments into a tuple.

Option D is true: **kwargs collects extra keyword arguments into a dictionary. Option E is false: you cannot mix *args and **kwargs arbitrarily; *args must come before **kwargs in definition.

214
MCQhard

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

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

items() in Python 3 returns a view that works similarly.

Why this answer

Option B is correct: in Python 3, dict.iteritems() is removed; use .items() which returns a view. Option A is wrong because dict.items() in Python 2 returns a list, but in Python 3 it returns a view, which is acceptable. Option C is wrong because dict.viewitems() does not exist in Python 3.

Option D is wrong because converting to list is unnecessary and not idiomatic.

215
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

216
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

217
MCQmedium

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

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

Invalid; starts with a digit.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

218
MCQmedium

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

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

Correct syntax.

Why this answer

The correct way uses 'and' for logical AND, and modulo operator for even check. Option A is correct.

219
Matchingmedium

Match each Python list method to its effect.

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

Concepts
Matches

Adds an item to the end of the list

Inserts an item at a given position

Removes the first occurrence of a value

Removes and returns an item at a given index

Sorts the list in ascending order in place

Why these pairings

These are common list methods for modifying list contents.

220
MCQmedium

A script uses a dictionary to store counts of words. The code `counts['apple'] += 1` raises a KeyError the first time because the key doesn't exist. Which approach best solves this?

A.Use `counts.setdefault('apple', 0)` then increment.
B.Use `try-except` to catch KeyError and then set the key.
C.Use `counts['apple'] = counts.get('apple') + 1`
D.Use `if 'apple' in counts:` before incrementing.
AnswerA

setdefault initializes if missing, then increment.

Why this answer

Option A is correct because `setdefault('apple', 0)` inserts the key with a default value of 0 if it does not exist, then returns the value (0). After that, `counts['apple'] += 1` increments safely. This avoids a KeyError without requiring an explicit check or exception handling, making it the most concise and Pythonic approach for initializing missing dictionary keys.

Exam trap

Python Institute often tests the misconception that `dict.get()` can be used directly in an increment expression, but candidates forget that `get` returns `None` for missing keys, leading to a TypeError rather than a KeyError.

How to eliminate wrong answers

Option B is wrong because while a try-except block can catch the KeyError, it is less efficient and more verbose than using `setdefault` or `defaultdict`; it also requires two separate operations (catch and set) instead of a single atomic method. Option C is wrong because `counts.get('apple')` returns `None` when the key is missing, and `None + 1` raises a TypeError, not a KeyError. Option D is wrong because it requires an explicit membership test and an extra assignment, which is more code and less efficient than `setdefault`; it also introduces a race condition in multithreaded contexts.

221
MCQmedium

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

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

Correct; the type is float.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

222
Multi-Selecteasy

Which TWO of the following are Python membership operators?

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

Membership operator.

Why this answer

Option B is correct because 'not in' is a Python membership operator that returns True if a value is not found in a sequence (like a list, tuple, or string). Option C is correct because 'in' is the complementary membership operator that returns True if a value is found in a sequence. Both are used to test membership in iterable objects.

Exam trap

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

223
MCQeasy

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

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

Underscore is allowed at start.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

Page 2

Page 3 of 7

Page 4

All pages