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

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

Page 6

Page 7 of 7

451
MCQmedium

A developer needs to swap the values of two variables a and b without using a temporary variable. Which single line of code correctly performs the swap?

A.a = b; b = a
B.a, b = b, a
C.a = a ^ b; b = a ^ b; a = a ^ b
D.a = a + b; b = a - b; a = a - b
AnswerB

Correct: tuple unpacking swaps values

Why this answer

Option B is correct because Python supports tuple unpacking, which allows swapping the values of two variables in a single line without a temporary variable. The expression `a, b = b, a` evaluates the right-hand side tuple `(b, a)` first, then assigns the values to `a` and `b` respectively, effectively swapping them.

Exam trap

Cisco often tests the distinction between a single-line swap using tuple unpacking and multi-line approaches (like XOR or arithmetic) that technically work but do not satisfy the 'single line' requirement, leading candidates to mistakenly choose those multi-line options.

How to eliminate wrong answers

Option A is wrong because `a = b; b = a` first overwrites `a` with `b`'s value, then assigns the now-overwritten `a` (which equals original `b`) to `b`, resulting in both variables holding the original `b` value, not a swap. Option C is wrong because it uses XOR bitwise operations across three lines, not a single line as required by the question. Option D is wrong because it uses arithmetic operations across three lines, not a single line as required by the question.

452
Multi-Selecthard

Which THREE of the following are valid ways to handle an exception in Python?

Select 3 answers
A.Using a `try` block with both `except` and `finally` blocks.
B.Using a `finally` block without a `try` block.
C.Using a `try` block with an `else` block but no `except` block.
D.Using a `try` block with a `finally` block.
E.Using a `try` block with one or more `except` blocks.
AnswersA, D, E

Combination is valid.

Why this answer

Option A is correct because Python's exception handling allows a `try` block to be followed by both `except` and `finally` blocks. The `except` block catches specific exceptions, while the `finally` block always executes (for cleanup), regardless of whether an exception occurred. This combination is fully valid and commonly used for robust resource management.

Exam trap

Python Institute often tests the rule that an `else` block cannot exist without at least one `except` block, and that a `finally` block must always be attached to a `try` block, leading candidates to mistakenly think these standalone constructs are valid.

453
MCQeasy

What is the data type of z?

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

Product of int and float is float.

Why this answer

The data type of z is float because the expression 10 / 3 performs true division in Python, which always returns a float even if the operands are integers. The result of 10 / 3 is approximately 3.3333333333333335, a floating-point number.

Exam trap

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

How to eliminate wrong answers

Option A is wrong because bool is a subtype of int in Python, but the result of 10 / 3 is not a boolean value (True or False). Option B is wrong because int would be the result of floor division (10 // 3) or integer division in some languages, but Python's / operator always returns a float. Option D is wrong because str is a string type, and the division operator does not produce a string; it produces a numeric float.

454
Multi-Selectmedium

Which THREE of the following are correct uses of the print() function?

Select 3 answers
A.print 'Hello'
B.print('Hello', 'World', sep='-')
C.print('Hello', 'World')
D.print('Hello')
E.print('Hello', 5)
AnswersB, C, D

Valid use of sep parameter.

Why this answer

Option B is correct because the print() function in Python 3 accepts a 'sep' keyword argument that specifies the separator between multiple arguments. Here, sep='-' causes the output to be 'Hello-World', demonstrating a valid and commonly used feature of print().

Exam trap

Python Institute often tests the distinction between Python 2's print statement (no parentheses) and Python 3's print function (requires parentheses), leading candidates to mistakenly select option A as valid.

455
Drag & Dropmedium

Order the steps to write a for loop that iterates over a range of numbers.

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

Steps
Order

Why this order

The for loop syntax is 'for variable in range(...):' with an indented body.

456
Multi-Selectmedium

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

Select 2 answers
A.for
B.2nd_value
C.value_2
D.val-ue
E._value
AnswersC, E

Valid: underscore and digits allowed (not at start)

Why this answer

Option C is correct because `value_2` starts with a letter and contains only letters, digits, and underscores, which satisfies Python's identifier rules. Python variable names must begin with a letter or underscore, and can include letters, digits, and underscores; `value_2` meets all these criteria.

Exam trap

Python Institute often tests the distinction between hyphens and underscores, as candidates mistakenly think hyphens are allowed in variable names because they are common in other contexts like file names or URLs.

457
MCQeasy

What does the following code output? try: x = int('abc') except ValueError: print('Invalid')

A.The program crashes
B.Invalid
C.(Nothing printed)
D.abc
AnswerB

The ValueError is raised and caught, printing 'Invalid'.

Why this answer

The code attempts to convert the string 'abc' to an integer using int(). Since 'abc' is not a valid integer, Python raises a ValueError. The except block catches this specific exception and executes print('Invalid'), so the output is 'Invalid'.

Option B is correct because the exception is handled gracefully without crashing.

Exam trap

Cisco often tests whether candidates understand that a caught exception does not crash the program; the trap here is that some candidates think any error causes a crash, but the except block prevents that.

How to eliminate wrong answers

Option A is wrong because the ValueError is explicitly caught by the except block, preventing the program from crashing; unhandled exceptions cause crashes, but here the exception is handled. Option C is wrong because the except block executes and prints 'Invalid', so something is printed. Option D is wrong because the code does not print the original string 'abc'; it prints the string 'Invalid' from the except block.

458
Multi-Selectmedium

Which two of the following are correct ways to create a dictionary in Python? (Choose two.)

Select 2 answers
A.my_dict = {a:1, b:2}
B.my_dict = dict(a=1, b=2)
C.my_dict = dict(['a',1],['b',2])
D.my_dict = {'a':1, 'b':2}
E.my_dict = ["a":1, "b":2]
AnswersB, D

Valid dict constructor.

Why this answer

A dictionary can be created with {} literal or with dict() constructor using keyword arguments. Options A and B are correct.

459
MCQmedium

Which code sorts a list of strings by their length in descending order? lst = ['aa', 'b', 'ccc']

A.sorted(lst, key=len, reverse=True)
B.sorted(lst, reverse=True)
C.sorted(lst, key=lambda s: len(s), reverse=True)
D.sorted(lst, key=lambda s: len(s))
AnswerC

Correct; sorts by length descending.

Why this answer

To sort by length descending, use the key parameter with a lambda function and set reverse=True. Option B does this.

460
Drag & Dropmedium

Arrange the steps to write and run a Python script from the command line in the correct order.

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

Steps
Order

Why this order

The process involves creating the script, saving it, opening a terminal, navigating to its location, and executing it with the Python interpreter.

461
MCQeasy

A developer writes code to compute the average of two numbers entered by the user: x = input('Enter first number: '); y = input('Enter second number: '); avg = (x + y) / 2. The program produces an error. What is the best practice to fix the code?

A.Convert the result to int after the operation: avg = int((x + y) / 2)
B.Use int() on the input() values: x = int(input(...)); y = int(input(...))
C.Use type casting in the division: avg = (float(x) + float(y)) / 2
D.Convert x and y to float before the operation: x = float(input(...)); y = float(input(...))
AnswerD

This ensures the addition and division work on numeric values.

Why this answer

Option D is correct because the `input()` function in Python always returns a string. When you use the `+` operator on two strings, it concatenates them (e.g., '5' + '3' = '53'), not adds them numerically. Dividing a concatenated string by 2 raises a TypeError.

The best practice is to convert both inputs to `float` immediately after receiving them, ensuring the subsequent arithmetic works correctly.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type, leading candidates to pick Option B (using `int`) or Option C (casting inside the expression), but the trap is that string concatenation happens before any conversion, so the error occurs at the `+` operator, not at the division.

How to eliminate wrong answers

Option A is wrong because it attempts to convert the result after the operation, but the error occurs earlier: `x + y` concatenates strings, and dividing a string by 2 raises a TypeError, so `int()` never executes. Option B is wrong because converting to `int` truncates any decimal input (e.g., 5.5 becomes 5), losing precision; for an average, `float` is more appropriate. Option C is wrong because while it converts inside the expression, it still concatenates strings first (`x + y` before `float()` is applied), causing the same TypeError; the conversion must happen before the addition.

462
MCQmedium

A data scientist needs to read a list of floats from a file, one per line, and compute the sum. The current code: total = 0.0 with open("data.txt") as f: for line in f: total = total + line print(total) When run, a TypeError occurs: unsupported operand type(s) for +: 'float' and 'str'. The scientist knows that line is a string. Which fix will correctly sum the numbers?

A.Change to: total = total + eval(line)
B.Change to: total = total + line.strip()
C.Change to: total = total + float(line.strip())
D.Change to: total = total + int(line)
AnswerC

float() converts the string to a number.

Why this answer

Option C is correct because `float(line.strip())` converts the string read from the file (after removing any surrounding whitespace, including the newline character) into a float, which can then be added to the float variable `total`. The original error occurs because Python does not allow implicit addition of a string to a float.

Exam trap

Python Institute often tests the candidate's understanding that file input is always a string and must be explicitly converted to a numeric type before arithmetic, and that `strip()` alone does not change the data type.

How to eliminate wrong answers

Option A is wrong because `eval(line)` is dangerous and unnecessary; it evaluates the string as a Python expression, which could execute arbitrary code and is not a safe or recommended way to convert a string to a float. Option B is wrong because `line.strip()` returns a string, not a float, so the same TypeError would occur when trying to add a string to a float. Option D is wrong because `int(line)` would fail if the line contains a decimal point (e.g., '3.14') and would also raise a ValueError; moreover, the data is floats, not integers.

463
MCQeasy

What is the result of the following expression? d = {'a': 1} d.get('b', 0)

A.0
B.None
C.KeyError
D.1
AnswerA

Correct; get returns the default 0.

Why this answer

The get method of a dictionary returns the value for the key if it exists, otherwise returns the default argument. Since 'b' is not a key, it returns 0.

464
MCQeasy

Refer to the exhibit. What type of exception occurred?

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

Correct; as shown in the traceback.

Why this answer

The traceback shows 'ZeroDivisionError: division by zero'. So the exception is ZeroDivisionError.

465
MCQhard

After executing: a = 5; b = 2; c = a // b; d = a % b; e = a ** b. What is the value of (c + d) * 2 - e?

A.-20
B.-19
C.-11
D.-15
AnswerB

Correct; see calculation.

Why this answer

After executing the code, a=5, b=2, c=5//2=2 (floor division), d=5%2=1 (remainder), e=5**2=25 (exponentiation). Then (c+d)*2-e = (2+1)*2-25 = 3*2-25 = 6-25 = -19. Option B is correct because it matches this calculation.

Exam trap

Python Institute often tests the distinction between floor division (//) and true division (/), and the correct order of operations (PEMDAS), where candidates may incorrectly compute c as 2.5 or misapply the exponentiation operator.

How to eliminate wrong answers

Option A is wrong because -20 would result if you mistakenly used regular division (c=2.5) and then rounded incorrectly, or if you swapped the order of operations (e.g., c+d*2-e). Option C is wrong because -11 would result if you incorrectly computed c as 5//2=2, d as 5%2=1, but then miscalculated e as 5**2=10 (confusing exponentiation with multiplication). Option D is wrong because -15 would result if you used integer division incorrectly (e.g., c=2, d=1, but then computed (c+d)*2 as 2+1*2=4, then 4-25=-21, or if you mistakenly used c=2, d=1, e=25 but then did (2+1)*2-25=6-25=-19, so -15 suggests a different arithmetic error like using c=5//2=2, d=5%2=1, e=5**2=25, but then computing (2+1)*2-25 as 2+1*2-25=2+2-25=-21, or mis-evaluating exponentiation as 5*2=10 leading to 6-10=-4, none of which match -15.

466
MCQeasy

A developer writes a program to calculate the average of three numbers: a=10; b=20; c=30; avg = a + b + c / 3; print(avg). What is the output?

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

Correct: operator precedence gives 10+20+10.0 = 40.0.

Why this answer

Option C is correct because the expression `a + b + c / 3` follows Python's operator precedence: division (`/`) has higher precedence than addition (`+`), so `c / 3` is evaluated first (30 / 3 = 10.0), then the additions are performed left to right: 10 + 20 + 10.0 = 40.0. The result is a float because division always returns a float in Python 3.

Exam trap

Python Institute often tests operator precedence by placing a division operation at the end of an expression without parentheses, tricking candidates into assuming left-to-right evaluation or that the entire sum is divided.

How to eliminate wrong answers

Option A is wrong because 20.0 would be the result if the expression were `(a + b + c) / 3` (average calculation), but the parentheses are missing. Option B is wrong because 10.0 would be the result if only `c / 3` were printed, ignoring `a` and `b`. Option D is wrong because 60.0 would be the result if the expression were `a + b + c` without division, or if the division were applied incorrectly to the entire sum without parentheses.

467
MCQhard

A Python program loads this JSON and accesses the first rule's action. Which expression gives the string "permit"?

A.data["rules"][0]["action"]
B.data["rules"][0]["action"][:5]
C.data["rules"][0]["action"][0]
D.data["rules"][1]["action"]
AnswerA

Correct: accesses first rule's action value.

Why this answer

Option A is correct because it uses the correct indexing to access the first element of the 'rules' list (index 0) and then retrieves the value associated with the key 'action' from that dictionary. This yields the string 'permit' as stored in the JSON data.

Exam trap

Python Institute often tests the distinction between accessing the first element of a list (index 0) versus the second element (index 1), and between retrieving a dictionary value by key versus slicing or indexing a string.

How to eliminate wrong answers

Option B is wrong because it attempts to slice the string 'permit' with [:5], which would return 'permit' only if the string length is exactly 5, but the correct approach is direct key access, not slicing. Option C is wrong because it uses index [0] on the string 'permit', which returns the first character 'p', not the whole string. Option D is wrong because it accesses the second rule (index 1) instead of the first rule (index 0), so it would retrieve the action of the second rule, which might not be 'permit'.

468
Matchingmedium

Match each Python data structure to its characteristic.

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

Concepts
Matches

Ordered, immutable sequence of items

Unordered collection of unique items

Mapping of key-value pairs

Ordered, mutable sequence of items

Immutable sequence of characters

Why these pairings

These are the fundamental data structures in Python with distinct properties.

469
Multi-Selecteasy

Which TWO of the following are valid methods that can be called on a tuple object? (Choose two.)

Select 2 answers
A..pop()
B..index()
C..append()
D..sort()
E..count()
AnswersB, E

index returns first index of a value.

Why this answer

Tuples have only two methods: count and index. Options B and C are correct. Option A is a list method.

Option D is a list method. Option E is a list method.

470
MCQeasy

A programmer needs to iterate over a list of strings and print each string in uppercase. Which loop correctly accomplishes this?

A.for i, item in enumerate(mylist): print(item.upper())
B.for item in mylist: item = item.upper()
C.for item in mylist: print(item.upper)
D.for i in range(len(mylist)): print(mylist[i].upper())
AnswerA, D

Also correct, but the question expects exactly one correct; both A and C are correct. I'll adjust: make only A correct? No, both are valid. I need to change distractors so that only one is correct. Let's replace A with a wrong one.

Why this answer

Option A is correct because it uses a for loop with enumerate to iterate over the list, and calls the string method upper() (with parentheses) to convert each item to uppercase before printing. This ensures each string is properly transformed and output.

Exam trap

Python Institute often tests the distinction between referencing a method (without parentheses) and calling it (with parentheses), leading candidates to pick Option C when they forget that methods must be invoked to execute.

How to eliminate wrong answers

Option B is wrong because it assigns the uppercase string to the loop variable item, but this does not modify the original list or print anything; the assignment has no visible effect. Option C is wrong because it prints the method object item.upper instead of calling it with parentheses, so it outputs a string representation of the bound method, not the uppercase string.

471
MCQmedium

What is the data type of the expression (3.14 > 2) and ('a' < 'b')?

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

Correct, logical operators return bool.

Why this answer

The expression (3.14 > 2) evaluates to True because 3.14 is greater than 2, and ('a' < 'b') evaluates to True because in Python string comparison uses lexicographic order based on Unicode code points ('a' has code point 97, 'b' has 98). The 'and' operator combines these two Boolean values, resulting in True, which is of type bool. Therefore, the entire expression's data type is bool.

Exam trap

Python Institute often tests the misconception that the 'and' operator returns a Boolean only when both operands are Boolean, but in Python it can return any operand type; however, in this specific case both operands are comparisons that yield bool, so the result is bool, and candidates may incorrectly think the result is int because True/False are subclasses of int.

How to eliminate wrong answers

Option B (float) is wrong because the expression does not produce a floating-point number; it produces a Boolean result from comparison and logical operators. Option C (str) is wrong because the expression involves comparisons and a logical operator, not string concatenation or manipulation, so the result is not a string. Option D (int) is wrong because while Booleans in Python are a subclass of int (True equals 1, False equals 0), the expression's type is explicitly bool, not int, and the question asks for the data type of the expression, which is bool.

472
MCQhard

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

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

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

Why this answer

In Python, the exponentiation operator ** is right-associative, meaning that `2 ** 3 ** 2` is evaluated as `2 ** (3 ** 2)`, not `(2 ** 3) ** 2`. First, `3 ** 2` equals 9, then `2 ** 9` equals 512. Thus, the correct output is 512.

Exam trap

The trap here is that candidates often assume left-to-right associativity for all operators, forgetting that ** is right-associative, leading them to pick 64 instead of 512.

How to eliminate wrong answers

Option B (12) is wrong because it incorrectly assumes addition or multiplication-like behavior, not exponentiation. Option C (64) is wrong because it results from left-associative evaluation `(2 ** 3) ** 2` = 8 ** 2 = 64, which is not how Python handles chained exponentiation. Option D (256) is wrong because it might come from miscomputing `2 ** 8` or confusing exponentiation with bitwise shifts.

473
MCQmedium

A developer writes: result = [x**2 for x in range(10) if x % 2 == 0]. What does this code produce?

A.A list of even numbers squared
B.A generator object
C.A list of squares of all numbers from 0 to 9
D.A list containing [0, 4, 16, 36, 64]
AnswerD

Correct: squares of even numbers 0,2,4,6,8.

Why this answer

The code uses a list comprehension with a conditional filter: `[x**2 for x in range(10) if x % 2 == 0]`. It iterates over numbers 0 through 9, keeps only even numbers (those where `x % 2 == 0`), squares each, and collects the results into a list. The resulting list is `[0, 4, 16, 36, 64]`, which are the squares of the even numbers 0, 2, 4, 6, and 8.

Exam trap

The trap here is that candidates may overlook the `if` filter and think the comprehension squares all numbers 0–9, or they may confuse list comprehensions with generator expressions, which use parentheses instead of square brackets.

How to eliminate wrong answers

Option A is wrong because it describes the result as 'a list of even numbers squared,' which is ambiguous and could be interpreted as the even numbers themselves being squared (which is true), but the phrasing is imprecise and the option does not list the actual values; the correct answer is the specific list. Option B is wrong because list comprehensions in Python produce a list object, not a generator object; a generator would require parentheses instead of square brackets (e.g., `(x**2 for x in range(10) if x % 2 == 0)`). Option C is wrong because it claims the list contains squares of all numbers from 0 to 9, but the `if x % 2 == 0` filter excludes odd numbers, so only even numbers are squared.

474
MCQmedium

A junior developer writes: print('Hello' + 5). This code raises an error. What is the best way to fix it?

A.print('Hello' * 5)
B.print('Hello' + str(5))
C.print('Hello', 5)
D.print('Hello' + '5')
AnswerB

Converts integer 5 to string and concatenates.

Why this answer

Option B is correct because Python's `+` operator for strings requires both operands to be strings. The code `print('Hello' + 5)` raises a `TypeError` because it attempts to concatenate a string with an integer. Using `str(5)` converts the integer to the string `'5'`, allowing the concatenation to succeed and print `Hello5`.

Exam trap

Python Institute often tests the distinction between concatenation (`+`) and multiple arguments in `print()`, where candidates may think `print('Hello', 5)` produces `Hello5` instead of `Hello 5` due to the default `sep=' '` parameter.

How to eliminate wrong answers

Option A is wrong because `'Hello' * 5` does not concatenate; it repeats the string 5 times, producing `HelloHelloHelloHelloHello`, which changes the intended output. Option C is wrong because `print('Hello', 5)` passes two separate arguments to `print()`, which prints them with a space separator (e.g., `Hello 5`), not as a single concatenated string. Option D is wrong because `'Hello' + '5'` works syntactically but does not fix the original error; it simply uses a string literal `'5'` instead of converting the integer `5`, which would still fail if the variable were truly an integer (e.g., from user input).

475
MCQeasy

Refer to the exhibit. What is the output?

A.3.0 1.0
B.3 3
C.3.333 1
D.3 1
AnswerD

Correct.

Why this answer

The expression `print(10/3, 10//3)` uses two different division operators in Python. The `/` operator performs true division and always returns a float, so `10/3` yields `3.3333333333333335` (displayed as `3.3333333333333335` or rounded to `3.333` depending on the environment, but the question expects `3.333`). The `//` operator performs floor division, which for positive numbers truncates the decimal part, so `10//3` yields `3`.

However, the correct answer is D (`3 1`) because the exhibit likely shows `print(10/3, 10%3)` — the modulo operator `%` returns the remainder of the division, which is `1`. The question's exhibit is misrepresented in the options; based on the correct answer D, the code must be `print(10/3, 10%3)`.

Exam trap

Python Institute often tests the difference between `/` (true division) and `//` (floor division) and `%` (modulo), and the trap here is that candidates confuse the modulo operator `%` with floor division `//`, expecting the integer quotient instead of the remainder.

How to eliminate wrong answers

Option A is wrong because `3.0 1.0` would result from `print(10/3, 10%3)` only if both results were explicitly cast to float, but `10%3` returns an integer `1`, not `1.0`. Option B is wrong because `3 3` would imply both operators returned integers, but `10/3` returns a float, not an integer. Option C is wrong because `3.333 1` would be the output of `print(10/3, 10%3)` only if the first value were truncated to three decimal places, but Python's default float representation does not round to three decimal places; it prints the full precision.

476
MCQhard

A company runs a script that processes user input temperatures. The script expects integers but sometimes users enter floats. The current code is: temp = int(input("Enter temperature: ")). When a user enters "36.5", the script crashes with a ValueError. The developer needs to modify the script to handle both integer and float inputs gracefully, converting the input to an integer (by truncation) for processing. Which of the following is the best course of action?

A.Use temp = int(float(input()))
B.Use input with a regex check to ensure only integers are entered.
C.Use a try-except block to catch ValueError and ask the user to re-enter.
D.Use float(input()) and do not convert to int, store as float.
AnswerA

Correct; float() accepts both int and float strings, int() truncates.

Why this answer

Option A is correct because it first converts the input string to a float (handling both integer and float strings), then truncates the float to an integer via int(). This gracefully processes inputs like '36.5' without crashing, meeting the requirement to truncate rather than round.

Exam trap

Python Institute often tests the misconception that int() can directly parse a string containing a decimal point, leading candidates to overlook the need for an intermediate float conversion.

How to eliminate wrong answers

Option B is wrong because using a regex to reject non-integer inputs would still crash on '36.5' (since it's not an integer), failing to handle floats gracefully. Option C is wrong because a try-except block that catches ValueError and asks for re-entry does not convert the float input to an integer by truncation; it rejects valid float input instead of processing it. Option D is wrong because storing the value as a float does not convert it to an integer as required; the script expects an integer for processing.

477
Multi-Selectmedium

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

Select 2 answers
A.(10 > 5) and (5 < 3)
B.not (0 or 1)
C.3 in [1,2,3] and 4 not in [1,2,3]
D.'a' in 'abc' or 5 > 10
E.(True and False) or (False or True)
AnswersC, E

Both conditions true.

Why this answer

Option C is correct because the expression `3 in [1,2,3]` evaluates to `True` (since 3 is an element of the list), and `4 not in [1,2,3]` also evaluates to `True` (since 4 is not present). The `and` operator requires both operands to be `True`, and here both are, so the entire expression is `True`.

Exam trap

Python Institute often tests the combination of membership operators (`in`, `not in`) with logical operators (`and`, `or`), and the trap here is that candidates may mis-evaluate option D as `False` because they focus on the `5 > 10` part, forgetting that `or` only needs one `True` operand, making the whole expression `True` — but the question expects only C and E as the two correct answers, so D is a distractor that is actually True but not selected.

478
MCQmedium

A student writes the code: x = 10; if x > 5: print("big"); else: print("small"). What is the output?

A.small
B.SyntaxError
C.big small
D.big
AnswerD

Condition true.

Why this answer

The code `x = 10; if x > 5: print("big"); else: print("small")` is syntactically correct in Python. Since `x` is 10, the condition `x > 5` evaluates to `True`, so the `if` branch executes, printing `"big"`. The semicolons are allowed as statement separators, and the colon after `if` and `else` is required.

Therefore, option D is correct.

Exam trap

Python Institute often tests whether candidates know that semicolons are valid statement separators in Python, leading many to incorrectly think they cause a `SyntaxError` when they do not.

How to eliminate wrong answers

Option A is wrong because `x = 10` makes the condition `x > 5` true, so `"small"` is not printed. Option B is wrong because the code uses semicolons to separate statements, which is valid Python syntax; there is no `SyntaxError`. Option C is wrong because only one branch executes — the `if` branch prints `"big"`, and the `else` branch is skipped, so only `"big"` is output, not both `"big"` and `"small"` on separate lines.

479
MCQmedium

What is the output of the code in the exhibit?

A.3
B.4
C.3.0
D.3.3333333333333335
AnswerA

Floor division of 10 by 3 yields 3.

Why this answer

The code performs integer division using the // operator, which in Python returns the floor of the division result for positive numbers. Since 10 // 3 equals 3 (the integer part of 10/3), the output is 3. Option A is correct because integer division discards the fractional part.

Exam trap

Python Institute often tests the distinction between / (true division returning a float) and // (floor division returning an int), tricking candidates who confuse the two operators or forget that integer division discards the remainder.

How to eliminate wrong answers

Option B is wrong because it assumes the result is 4, which would only occur if the code used ceiling division or an incorrect operation. Option C is wrong because it outputs 3.0, which would result from true division (/) rather than integer division (//). Option D is wrong because it outputs the full floating-point result of 10/3 (3.3333333333333335), which is produced by the / operator, not the // operator.

480
MCQmedium

A system administrator is writing a Python script to monitor server uptime. The script reads a log file line by line, parses timestamps, and stores them in a list. It then loops through the list to detect gaps longer than 5 minutes that indicate a crash. However, the script keeps missing crashes. The current loop is a for loop that iterates over the list using indices. The administrator suspects the loop logic. The loop uses 'for i in range(len(timestamps)-1): if timestamps[i+1] - timestamps[i] > 300: print("Crash detected")'. Timestamps are integers representing seconds since epoch. What is the most likely cause of missed crashes and the best fix?

A.The loop should use range(len(timestamps)) instead of -1
B.The difference should be computed as timestamps[i] - timestamps[i+1]
C.The comparison should be > 300, but use > 300.0
D.The timestamps list may not be sorted
AnswerD

Unsorted timestamps lead to inaccurate gap detection. Sorting before loop fixes it.

Why this answer

Option D is correct because the loop assumes timestamps are in chronological order, but if the list is unsorted, adjacent elements may not represent consecutive events, causing the time difference to be negative or misleading, and thus missing actual gaps. Sorting the list before the loop ensures that timestamps[i+1] - timestamps[i] correctly reflects the time between consecutive log entries.

Exam trap

Python Institute often tests the assumption that data structures are in the expected order, and the trap here is that candidates focus on off-by-one errors or type issues while overlooking the fundamental requirement that the list must be sorted for pairwise difference logic to work.

How to eliminate wrong answers

Option A is wrong because using range(len(timestamps)) would cause an IndexError on the last iteration when accessing timestamps[i+1]. Option B is wrong because subtracting timestamps[i] from timestamps[i+1] (assuming sorted order) gives a positive difference for increasing timestamps, which is correct; reversing the order would yield negative values that never exceed 300. Option C is wrong because comparing integers with > 300 is functionally identical to > 300.0 in Python; the type mismatch does not affect comparison logic.

481
MCQmedium

Which of the following is a valid Python variable name?

A.my-var
B.for
C._data2
D.2nd_value
AnswerC

Starts with underscore, valid.

Why this answer

Option C (_data2) is correct because Python variable names must start with a letter or an underscore, and can contain letters, digits, and underscores. _data2 begins with an underscore followed by valid characters, making it a legal identifier.

Exam trap

Python Institute often tests the rule that hyphens are invalid in variable names (confusing them with underscores) and that keywords like 'for' cannot be used as identifiers, leading candidates to mistakenly choose options that look familiar from other languages.

How to eliminate wrong answers

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

482
MCQmedium

Given the tuple t = (1, 2, 3, 4, 5), which expression returns the last element?

A.t[-1]
B.t[5]
C.t[4]
D.t[0]
AnswerA

Negative index -1 refers to the last element.

Why this answer

In Python, negative indices count from the end of a sequence. For the tuple t = (1, 2, 3, 4, 5), t[-1] accesses the last element (5), because -1 refers to the final position. This is a standard feature of Python's sequence indexing.

Exam trap

Python Institute often tests the distinction between zero-based indexing and negative indexing, trapping candidates who mistakenly think t[5] or t[4] is the correct way to access the last element without considering index out-of-range or dynamic length scenarios.

How to eliminate wrong answers

Option B is wrong because t[5] attempts to access index 5, which is out of range for a tuple with indices 0 through 4, raising an IndexError. Option C is wrong because t[4] returns the element at index 4, which is 5, but this is the last element only coincidentally; the question asks for an expression that returns the last element in general, and t[4] is not a robust way to do it if the tuple length changes. Option D is wrong because t[0] returns the first element (1), not the last.

483
Multi-Selectmedium

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

Select 2 answers
A.for
B.my-var
C.1var
D._private
E.my_var
AnswersD, E

Leading underscore is allowed.

Why this answer

Options A and D are valid. Option A uses underscore and letters. Option D uses a leading underscore.

Option B is invalid because it starts with a digit. Option C is invalid because it contains a hyphen. Option E is invalid because it is a reserved keyword.

484
Multi-Selecteasy

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

Select 2 answers
A.1st_value
B.my_var_2
C.user@name
D._private
E.for
AnswersB, D

Valid: letters, digits, underscores, not starting with digit.

Why this answer

Option A is incorrect because variable names cannot start with a digit. Option B is incorrect because 'for' is a reserved keyword. Option C is correct: underscores are allowed.

Option D is correct: names can start with underscore. Option E is incorrect because '@' is not allowed in identifiers.

485
MCQhard

Refer to the exhibit. What is the output?

A.[1] [2] [3]
B.Error: default argument is mutable
C.[1] [1, 2] [1, 2, 3]
D.[1] [2] [1, 3]
AnswerD

Correct; default list persists across calls.

Why this answer

First call uses default list, returns [1]. Second call passes a new empty list, so returns [2]. Third call uses the same default list (now [1]), so returns [1, 3].

486
MCQeasy

A Python script contains the following line: x = 5. Later in the script, the programmer wants to check if x is an integer. Which of the following is the BEST way to perform this check?

A.if isinstance(x, int):
B.if x is integer:
C.if x == 'integer':
D.if type(x) == int:
AnswerA

Correct and Pythonic.

Why this answer

Option A is correct because `isinstance(x, int)` is the recommended way to check if a variable is an instance of a specific class in Python. It handles inheritance correctly (e.g., if `x` were a subclass of `int`) and is more robust than directly comparing types with `type()`. This aligns with Python's duck typing philosophy and is the standard approach in professional code.

Exam trap

Python Institute often tests the distinction between `type()` and `isinstance()`, and the trap here is that candidates may think `type(x) == int` is equivalent to `isinstance(x, int)`, not realizing that `isinstance` handles inheritance and is the Pythonic standard.

How to eliminate wrong answers

Option B is wrong because `is` is an identity operator in Python, not a type-checking keyword, and `integer` is not a built-in type name (the correct name is `int`). Option C is wrong because it compares `x` to the string `'integer'`, which will always be `False` unless `x` is literally that string. Option D is wrong because `type(x) == int` does not account for subclasses of `int`; for example, if `x` were an instance of a subclass of `int`, this check would return `False`, whereas `isinstance()` would return `True`.

487
MCQmedium

A company needs to process user input that must be a whole number between 1 and 100. Which code snippet correctly validates and converts the input?

A.num = int(input("Enter: ")); if 1 <= num <= 100: ...
B.num = int(input("Enter: ")); if num in range(1,101): ...
C.num = input("Enter: "); if num.isdigit() and 1 <= int(num) <= 100: ...
D.All of the above are correct.
AnswerC

Checks if input is digit first, then converts safely.

Why this answer

Option C is correct because it first checks that the input string consists only of digits using `isdigit()`, which prevents `ValueError` from non-numeric input, and then safely converts to `int` only after validation. This ensures the input is a whole number between 1 and 100 before any further processing.

Exam trap

Python Institute often tests the misconception that `int(input(...))` is safe as long as you later check the value, but the trap is that the conversion itself can raise a `ValueError` before any validation occurs, making Options A and B incorrect.

How to eliminate wrong answers

Option A is wrong because calling `int(input(...))` directly will raise a `ValueError` if the user enters non-numeric input (e.g., letters or symbols), crashing the program before any validation occurs. Option B is wrong for the same reason — it also calls `int()` on raw input without checking, leading to a `ValueError` on invalid input. Option D is wrong because not all of the above are correct; only Option C handles input validation safely.

488
MCQhard

What is the scope of a variable defined inside a function?

A.Global
B.Built-in
C.Local
D.Nonlocal
AnswerC

Limited to the function.

Why this answer

Option A is correct because variables defined inside a function have local scope. Option B is wrong because global scope requires the global keyword. Option C is wrong because built-in scope is for pre-defined names.

Option D is wrong because nonlocal is used for nested functions.

489
Multi-Selectmedium

Which TWO of the following are valid ways to merge two dictionaries in Python 3.5+? (Assume dict1 = {'a':1} and dict2 = {'b':2})

Select 2 answers
A.dict1 | dict2
B.dict1.update(dict2)
C.dict1 + dict2
D.dict1.merge(dict2)
E.{**dict1, **dict2}
AnswersB, E

The update method merges dict2 into dict1, modifying dict1 in place.

Why this answer

The valid ways are A and B. A (update) modifies dict1 in place. B (unpacking) creates a new dictionary.

C is not valid because dictionaries do not support +. D is not a built-in method. E (the | operator) is new in Python 3.9 and may not be available in older versions, so it is not considered a general solution.

490
MCQmedium

A data analyst has a list of temperature readings in Celsius and wants to create a new list containing only readings that are valid (>= -273.15 and <= 1000). Which code correctly creates the filtered list?

A.valid = [temp for temp in temps if -273.15 <= temp <= 1000]
B.valid = [temp for temp in temps if temp > -273.15 and temp < 1000]
C.valid = [] for t in temps: if t > -273.15 and t < 1000: valid.append(t)
D.valid = list(filter(lambda t: t >= -273.15, temps))
AnswerA

Correct; uses chained comparison to include boundaries.

Why this answer

Option A is correct because it uses a list comprehension with a chained comparison (`-273.15 <= temp <= 1000`) that correctly includes both boundary values. This syntax is Pythonic and ensures temperatures equal to -273.15 or 1000 are considered valid, matching the requirement exactly.

Exam trap

Python Institute often tests the distinction between inclusive (`<=`, `>=`) and exclusive (`<`, `>`) comparisons, and the trap here is that candidates may overlook the boundary values or choose a syntactically incorrect loop structure like Option C.

How to eliminate wrong answers

Option B is wrong because it uses strict inequalities (`>` and `<`) instead of `>=` and `<=`, which excludes the boundary values -273.15 and 1000, failing the requirement. Option C is wrong because it uses invalid Python syntax: the list initialization and `for` loop are not separated by a newline or semicolon, and the indentation is missing, making it a syntax error. Option D is wrong because it only filters for `t >= -273.15` but does not enforce the upper bound of `<= 1000`, so temperatures above 1000 would be incorrectly included.

491
Multi-Selecteasy

Which TWO of the following exceptions are built-in Python exceptions? (Select exactly 2)

Select 2 answers
A.ZeroDivisionError
B.KeyError
C.StringError
D.NumberError
E.ListError
AnswersA, B

Built-in exception for division by zero.

Why this answer

Option A is correct because ZeroDivisionError is a built-in Python exception that is raised when the second operand of a division or modulo operation is zero. It is part of Python's standard exception hierarchy and is commonly encountered in arithmetic operations.

Exam trap

Python Institute often tests the distinction between built-in exceptions and non-existent exceptions like StringError, NumberError, or ListError, which are not part of Python's standard library, to catch candidates who guess based on naming patterns rather than actual Python knowledge.

492
MCQmedium

What is the output when the code is executed?

A.Cannot divide by zero
B.The program crashes with an unhandled exception
C.Result: 0
D.Unsupported operand
AnswerA

ZeroDivisionError is caught.

Why this answer

Option A is correct because the code attempts to divide by zero, which raises a ZeroDivisionError. Python's default exception handling prints 'Cannot divide by zero' if the exception is caught, or the program would crash if unhandled. The question implies the code includes a try-except block that catches this specific error and prints that message.

Exam trap

Python Institute often tests the distinction between an unhandled exception (crash) and a caught exception (graceful handling), tricking candidates who assume any division by zero always crashes the program.

How to eliminate wrong answers

Option B is wrong because the program does not crash with an unhandled exception; the ZeroDivisionError is caught by the try-except block, so execution continues gracefully. Option C is wrong because division by zero does not yield 0; Python raises an exception instead of returning a numeric result. Option D is wrong because 'Unsupported operand' is not a Python error message; the actual error is ZeroDivisionError, which occurs when the divisor is zero, not due to operand type mismatch.

493
MCQmedium

A developer needs to implement a loop that prints numbers from 10 down to 1. Which loop correctly achieves this?

A.for i in range(10, 0, -1): print(i)
B.for i in range(10, 0): print(i)
C.for i in reversed(range(1, 10)): print(i)
D.for i in range(10, 1, -1): print(i)
AnswerA

Correct; step -1 from 10 down to 1.

Why this answer

Option A is correct because `range(10, 0, -1)` generates numbers from 10 down to 1 inclusive. The start is 10, the stop is 0 (exclusive), and the step is -1, so the sequence is 10, 9, 8, ..., 1. This matches the requirement exactly.

Exam trap

Python Institute often tests the exclusive nature of the stop argument in `range()`, leading candidates to forget that the stop value is never included in the sequence.

How to eliminate wrong answers

Option B is wrong because `range(10, 0)` defaults to a step of 1, and since start > stop with a positive step, it produces an empty sequence — nothing is printed. Option C is wrong because `reversed(range(1, 10))` yields numbers from 9 down to 1, missing 10 entirely. Option D is wrong because `range(10, 1, -1)` stops at 2 (since stop is exclusive), so it prints 10 down to 2, missing 1.

494
MCQmedium

Refer to the exhibit. What is the output?

A.1 2 [3, 4] {'x': 5, 'y': 6}
B.1 2 (3, 4) {}
C.1 2 3 4 5 6
D.1 2 (3, 4) {'x': 5, 'y': 6}
AnswerD

Correct; args are in a tuple, kwargs in a dict.

Why this answer

a=1, b=2, args receives (3,4) as a tuple, kwargs receives {'x':5, 'y':6} as a dict.

495
MCQeasy

Which loop is more efficient for iterating over a large list when you only need the values, not indices?

A.for i in range(len(mylist)): value = mylist[i]
B.for i, value in enumerate(mylist):
C.for value in mylist:
D.for value in mylist[::-1]:
AnswerC

Direct iteration over values is most efficient.

Why this answer

Option C is correct because iterating directly over the list with `for value in mylist:` avoids the overhead of indexing or enumeration. This is the most efficient approach in Python for accessing only the values, as it uses the list's internal iterator, which is implemented in C and involves no function calls or index lookups per iteration.

Exam trap

Python Institute often tests the misconception that `enumerate()` is always the best choice for iteration, but the trap here is that candidates overlook the specific requirement ('only the values, not indices') and choose a more general but less efficient option like B or A.

How to eliminate wrong answers

Option A is wrong because it uses `range(len(mylist))` and then accesses each element via indexing (`mylist[i]`), which adds the overhead of calling `range()` and performing a list lookup each iteration, making it less efficient. Option B is wrong because `enumerate()` yields both index and value, which is unnecessary when only values are needed, adding the overhead of tuple unpacking and an extra counter. Option D is wrong because `mylist[::-1]` creates a reversed copy of the entire list in memory, which is both time- and space-inefficient for large lists, and then iterates over that copy.

496
MCQmedium

Refer to the exhibit. What type of error occurred, and which line caused it?

A.NameError at line 3
B.SyntaxError at line 1
C.ValueError at line 0
D.ZeroDivisionError at line 3
AnswerD

The output explicitly states ZeroDivisionError on line 3.

Why this answer

Option C is correct: The traceback clearly shows ZeroDivisionError on line 3. Option A is wrong because it's not a syntax error. Option B is wrong because it's not a NameError.

Option D is wrong because it's not a ValueError.

497
MCQhard

Refer to the exhibit. What is the output of Line C?

A.TypeError
B.30
C.33
D.10
AnswerC

Correct. 1+2+10+20 = 33.

Why this answer

The function func has parameters a, b (required) and c, d (optional with defaults 10 and 20). Line C calls func with only two arguments (1 and 2), so c and d take their default values. The result is 1+2+10+20 = 33.

498
Drag & Dropmedium

Arrange the steps to handle an exception in Python using try-except.

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

Steps
Order

Why this order

Exception handling wraps risky code in try, catches exceptions with except, and optionally includes else and finally.

499
MCQmedium

Refer to the exhibit. What is the output?

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

Only indices with even values (1 and 3) are squared.

Why this answer

The loop iterates over indices. For even values (2,4), they are squared: 2->4, 4->16. Others unchanged.

Result: [1,4,3,16,5]. Option C is correct.

500
MCQeasy

A dictionary student = {'name': 'John', 'age': 20}. To safely get the grade with a default of 'N/A', which code should be used?

A.student.get('grade', 'N/A')
B.student['grade']
C.student.fetch('grade', 'N/A')
D.student['grade'] or 'N/A'
AnswerA

Correct: get returns 'N/A' if 'grade' is not present.

Why this answer

Option A is correct because the `get()` method of a dictionary safely retrieves the value for a given key, returning a default value (here `'N/A'`) if the key does not exist. This avoids raising a `KeyError` when the key `'grade'` is missing from the dictionary.

Exam trap

Python Institute often tests the distinction between safe dictionary access methods (`get()`) and direct indexing (`[]`), trapping candidates who think the `or` operator can short-circuit a `KeyError` or who invent non-existent methods like `fetch()`.

How to eliminate wrong answers

Option B is wrong because using `student['grade']` directly raises a `KeyError` if the key `'grade'` does not exist, which is not safe. Option C is wrong because dictionaries have no `fetch()` method; this is not a valid Python dictionary operation. Option D is wrong because `student['grade'] or 'N/A'` still evaluates `student['grade']` first, which raises a `KeyError` if the key is missing, and the `or` expression never executes.

501
Matchingmedium

Match each Python concept to its description.

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

Concepts
Matches

A name that references a value in memory

A block of reusable code that performs a specific task

A file containing Python definitions and statements

A collection of modules organized in directories

A blueprint for creating objects

Why these pairings

These are key concepts in Python programming that help organize code.

502
MCQmedium

A program needs to print the index and value of each item in a list named 'items'. Which code snippet correctly does this?

A.for i, item in enumerate(items): print(i, item)
B.Both A and B are correct
C.for i in range(len(items)): print(i, items[i])
D.for item in items: print(items.index(item), item)
AnswerB

Both snippets correctly print index and value.

Why this answer

Option B is correct because both `for i, item in enumerate(items): print(i, item)` and `for i in range(len(items)): print(i, items[i])` correctly iterate over the list while printing the index and value. `enumerate()` is the Pythonic way, but `range(len())` is also valid and commonly used in PCEP-level questions.

Exam trap

Python Institute often tests the misconception that `items.index(item)` is a reliable way to get the current index, but it fails with duplicate values and is computationally expensive, leading candidates to incorrectly select option D.

How to eliminate wrong answers

Option A is wrong because it is actually correct, but the question states 'Both A and B are correct' as the answer, so A alone is not the full correct choice. Option C is wrong because it is also correct, but again not the full answer. Option D is wrong because `items.index(item)` returns the first occurrence of the value, which will produce incorrect indices if the list contains duplicate values; it is also inefficient and not the intended way to access both index and value.

503
MCQeasy

A developer needs to determine the number of elements in a tuple named 't'. Which code snippet will correctly return the length?

A.t.append(5)
B.t[0] = 5
C.len(t)
D.t.pop()
AnswerC

The built-in len() function returns the number of elements in a tuple.

Why this answer

Option B (len(t)) is the correct way to get the length of a tuple. Option A attempts to assign a value to a tuple element, which is not allowed because tuples are immutable. Option C uses append(), which is a list method, not a tuple method.

Option D uses pop(), which also works only on lists.

504
MCQmedium

Consider the following code: def foo(x, y): return x * y result = foo(y=2, 3) What is the error?

A.The function requires at least one argument but none provided.
B.A positional argument follows a keyword argument.
C.Keyword arguments cannot be used in function calls.
D.The function definition has too many parameters.
AnswerB

In Python, positional arguments must come before any keyword arguments.

Why this answer

Option B is correct because in Python, when calling a function, all positional arguments must appear before any keyword arguments. The call `foo(y=2, 3)` violates this rule by placing a positional argument (`3`) after a keyword argument (`y=2`), which raises a SyntaxError. This is enforced by Python's parser to avoid ambiguity in argument binding.

Exam trap

Cisco often tests the rule that positional arguments must precede keyword arguments in a function call, and the trap here is that candidates may mistakenly think the error is about missing arguments or invalid keyword usage, rather than the ordering violation.

How to eliminate wrong answers

Option A is wrong because the function call does provide arguments (a keyword argument `y=2` and a positional argument `3`), so the error is not about missing arguments. Option C is wrong because keyword arguments are fully supported in Python function calls and are commonly used for clarity and optional parameters. Option D is wrong because the function definition `def foo(x, y)` has exactly two parameters, which matches the number of arguments provided; the error is in the call syntax, not the definition.

505
MCQhard

What is the result of the expression: (1 and 0) or (not False and True)?

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

The or operation returns True because the second part is truthy.

Why this answer

1 and 0 evaluates to 0 (falsy). not False evaluates to True, so not False and True evaluates to True. 0 or True evaluates to True (the last truthy value).

506
MCQmedium

A programmer needs to swap the values of two variables a and b without using a temporary variable. Which approach works in Python?

A.a = b; b = a
B.a, b = b, a
C.a = a ^ b; b = a ^ b; a = a ^ b
D.a = b + a; b = a - b; a = a - b
AnswerB

Correct: Python's tuple unpacking swaps values.

Why this answer

Option B is correct because Python supports tuple unpacking, which allows the values of a and b to be swapped in a single atomic operation: a, b = b, a. This works by creating a tuple (b, a) on the right-hand side, then unpacking it into the variables on the left, effectively swapping the values without a temporary variable.

Exam trap

Python Institute often tests the misconception that simple sequential assignment (a = b; b = a) works for swapping, leading candidates to overlook Python's tuple unpacking mechanism.

How to eliminate wrong answers

Option A is wrong because a = b; b = a first overwrites a with b's value, then assigns the new a (which is now b) to b, so both variables end up with the original b value, failing to swap. Option C is wrong because while a = a ^ b; b = a ^ b; a = a ^ b works in languages like C with mutable integers, Python's integers are immutable and the XOR operation on integers does not modify variables in place; the code would actually work in Python due to rebinding, but it is not a recommended or readable approach and can fail with large integers due to Python's arbitrary precision. Option D is wrong because a = b + a; b = a - b; a = a - b works only if the sum does not overflow, but Python integers are arbitrary precision so overflow is not an issue; however, this approach is fragile with floating-point numbers and is not the idiomatic Python way.

507
Multi-Selecthard

Which three of the following statements about lists are true? (Choose three.)

Select 3 answers
A.Lists can be indexed with integers.
B.Lists can be sliced to create a new list.
C.Lists are mutable.
D.Lists have a fixed size once created.
E.Lists can only contain elements of the same data type.
AnswersA, B, C

Indexing starts at 0.

Why this answer

Option A is correct because lists in Python are ordered sequences that support indexing with integers, starting from 0 for the first element and negative integers for reverse indexing. This allows direct access to any element by its position, a fundamental feature of sequence types in Python.

Exam trap

Python Institute often tests the misconception that lists are fixed-size or homogeneous, similar to arrays in other languages, to catch candidates who confuse Python lists with static arrays or typed collections.

508
MCQmedium

A developer is writing a program to calculate the average of three test scores. The current code reads scores as integers: a=int(input()); b=int(input()); c=int(input()); avg = (a+b+c)/3; print(avg). For scores 7, 8, and 9, the output is 8.0, but the requirement is to print the integer average (8), rounded to the nearest whole number. Which modification should the developer make to meet the requirement?

A.Use integer division after multiplying sum
B.Use integer division: avg = (a+b+c)//3
C.Use int(avg): print(int(avg))
D.Use round(avg): print(round(avg))
AnswerD

Correct; round rounds to nearest integer.

Why this answer

The requirement is to print the integer average rounded to the nearest whole number. Using `round(avg)` correctly rounds the floating-point result (8.0) to the nearest integer (8) and prints it as an integer, satisfying the requirement. Option D is correct because `round()` performs standard rounding (banker's rounding in Python 3) and returns an integer when called with a single argument.

Exam trap

Python Institute often tests the distinction between truncation (`int()`) and rounding (`round()`), leading candidates to mistakenly choose `int(avg)` because they think converting to int removes decimals, but it truncates rather than rounds.

How to eliminate wrong answers

Option A is wrong because multiplying the sum and then using integer division (e.g., `(a+b+c)*1//3`) does not round to the nearest whole number; it truncates toward negative infinity, which would give 8 for 7,8,9 but fails for cases like 7,8,8 (sum 23, average 7.666, truncates to 7 instead of rounding to 8). Option B is wrong because `(a+b+c)//3` performs floor division, which truncates the decimal part (e.g., 24//3 = 8 for 7,8,9, but for 7,8,8 it gives 7 instead of the rounded 8). Option C is wrong because `int(avg)` truncates the decimal part (e.g., 8.999 becomes 8, not rounded to 9), which does not meet the 'rounded to the nearest whole number' requirement.

509
MCQeasy

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

A._myvar
B.myVar2
C.2nd_var
D.my_var
AnswerC

Invalid; names cannot start with a digit.

Why this answer

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

Exam trap

Cisco often tests the rule that variable names cannot start with a digit, knowing that candidates may mistakenly think digits are allowed anywhere or that underscores are not valid starting characters.

How to eliminate wrong answers

Option A is wrong because '_myvar' is a valid variable name; it starts with an underscore, which is allowed, and contains only letters and underscores. Option B is wrong because 'myVar2' is valid; it starts with a letter and contains letters and digits, which is permitted. Option D is wrong because 'my_var' is valid; it starts with a letter and uses an underscore, both of which are allowed in Python identifiers.

510
MCQmedium

What is the output of the following code? print('Hello', 'World', sep='-', end='!\n')

A.Hello-World\n
B.Hello-World!\n
C.Hello World!\n
D.Hello World!\n
AnswerB

Correct: 'Hello' and 'World' separated by '-', ending with '!' and newline

Why this answer

The `print()` function with `sep='-'` replaces the default space separator with a hyphen between the two arguments 'Hello' and 'World', producing 'Hello-World'. The `end='!\n'` parameter overrides the default newline-only end with an exclamation mark followed by a newline, so the output ends with '!' before the newline. Therefore, the correct output is 'Hello-World!\n'.

Exam trap

The trap here is that candidates often overlook the `end` parameter override and assume the default newline-only ending, or they confuse `sep` with `end`, leading them to pick an option with a space separator or missing the exclamation mark.

How to eliminate wrong answers

Option A is wrong because it omits the exclamation mark specified by `end='!\n'`, showing only the default newline. Option C is wrong because it uses a space separator instead of the hyphen specified by `sep='-'`. Option D is wrong for the same reason as C (space instead of hyphen) and also omits the exclamation mark.

Page 6

Page 7 of 7

All pages