Courseiva

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

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

Page 6

Page 7 of 7

451
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

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.

452
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

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

453
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 on a dictionary returns the value for the given key if it exists; otherwise, it returns the default value provided as the second argument. Since key `'b'` is not in dictionary `d`, the method returns `0` (the specified default). Option A is correct because `d.get('b', 0)` explicitly supplies a default of `0`.

Exam trap

The PCEP exam often tests the distinction between `dict.get()` (which returns a default or `None`) and direct subscript access `d[key]` (which raises `KeyError`), trapping candidates who confuse the two behaviors.

How to eliminate wrong answers

Option B is wrong because `get()` returns `None` only when no default is provided and the key is missing; here a default of `0` is given. Option C is wrong because `get()` never raises a `KeyError` — that would occur with direct indexing like `d['b']`. Option D is wrong because `1` is the value for key `'a'`, not for key `'b'`.

454
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 code attempts to divide by zero (e.g., `10 / 0`), which raises a `ZeroDivisionError` in Python. This is a specific built-in exception for division or modulo operations where the divisor is zero.

Exam trap

The PCEP exam often tests the distinction between the generic `ArithmeticError` and its specific subclass `ZeroDivisionError`, trapping candidates who think the parent class is raised directly instead of the more specific exception.

How to eliminate wrong answers

Option B is wrong because `TypeError` occurs when an operation or function is applied to an object of inappropriate type, not when dividing by zero. Option C is wrong because `ValueError` occurs when a function receives an argument with the right type but an inappropriate value (e.g., `int('abc')`), not for division by zero. Option D is wrong because `ArithmeticError` is a base class for arithmetic-related exceptions, but Python raises the more specific `ZeroDivisionError` (a subclass of `ArithmeticError`) for division by zero, not the parent class directly.

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

456
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

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.

457
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

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

458
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

Python data structures have distinct properties: lists and tuples are ordered sequences (lists mutable, tuples immutable); sets are unordered and contain unique elements; dictionaries map keys to values. Common confusions include mixing mutability/order between lists and tuples, and assuming sets maintain order.

459
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

The `.index()` method is a built-in tuple method that returns the index of the first occurrence of a specified value. Tuples are immutable sequences, so they support only non-mutating methods like `.index()` and `.count()`, which do not modify the tuple.

Exam trap

The PCEP exam often tests the distinction between mutable and immutable sequence types, trapping candidates who assume that because lists have methods like `.pop()`, `.append()`, and `.sort()`, tuples must have them too, when in fact tuples only support non-mutating methods like `.index()` and `.count()`.

460
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()) [CORRECT]
AnswerA, D

Correct: prints item.upper() for each item, works but has an unused enumeration index.

Why this answer

Both Option A and Option D correctly iterate over the list and print each string in uppercase. Option A uses enumerate to get each item and calls item.upper() with parentheses, printing the result. Although it introduces an unused index variable i, it still works correctly.

Option D uses range(len(mylist)) to access each element by index and prints mylist[i].upper(). Option B fails because it does not print the result; it only reassigns the variable. Option C omits the parentheses on upper(), printing the method object instead of the string.

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.

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

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

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

464
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

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

465
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 code in the exhibit is `print(10//3, 10%3)`. The `//` operator performs floor division, which for positive numbers truncates the decimal part, so `10//3` yields 3. The `%` operator returns the remainder of the division, `10%3` yields 1.

Thus the output is '3 1'.

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.

466
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

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.

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

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

469
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

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.

470
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

(_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.

471
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

A common trap in PCEP exams is that candidates may use a hardcoded index like t[4] which works for this specific tuple but fails if the tuple length changes. The correct dynamic way is t[-1], which always references the last element regardless of tuple length.

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.

472
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

(_private) is correct because underscores are allowed in Python variable names, including at the start. Python identifiers can contain letters, digits, and underscores, but must not begin with a digit. A leading underscore is a valid naming convention for internal or private attributes.

Exam trap

The PCEP exam often tests the rule that hyphens are not allowed in variable names (unlike in some other languages or filenames), leading candidates to mistakenly think 'my-var' is valid because it looks like a common naming pattern.

473
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

Variable names in Python must start with a letter or underscore, and can contain letters, digits, and underscores. 'my_var_2' starts with a lowercase letter and uses only underscores and digits, making it a valid identifier.

Exam trap

The PCEP exam often tests the rule that variable names cannot start with a digit, and the fact that keywords are reserved, to trap candidates who overlook these fundamental syntax rules.

474
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

The function uses a mutable default argument `lst=[]`. On the first call, `append_to_list(1)` uses the default list and appends 1, returning `[1]`. On the second call, `append_to_list(2, [])` passes an explicit empty list, so it appends 2 to that new list, returning `[2]`.

On the third call, `append_to_list(3)` uses the default list again, which now contains `[1]` from the first call, so appending 3 yields `[1, 3]`. Thus the output is `[1] [2] [1,3]` printed on separate lines.

Exam trap

The PCEP exam often tests the mutable default argument trap, where candidates mistakenly believe each function call creates a fresh default list, rather than understanding that the default object is created once and reused, leading to cumulative modifications across calls.

How to eliminate wrong answers

Option A is wrong because it assumes each call creates a new list, ignoring Python's mutable default argument behavior where the same list object is reused across calls without an argument. Option B is wrong because Python does not raise an error for mutable default arguments; it is a common pitfall but syntactically and semantically valid. Option C is wrong because it incorrectly suggests the second call returns `[2]` instead of `[1, 2]`, misunderstanding that the default list persists and accumulates values from previous calls.

475
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

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

476
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

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.

477
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

In Python, any variable assigned inside a function (without global or nonlocal declarations) has local scope. This means it is only accessible within that function's block and is destroyed when the function returns, as per Python's LEGB (Local, Enclosing, Global, Built-in) rule.

Exam trap

The PCEP exam often tests the misconception that any variable inside a function is automatically global or that 'nonlocal' applies to simple (non-nested) functions, leading candidates to pick 'Global' or 'Nonlocal' instead of 'Local'.

How to eliminate wrong answers

Option A is wrong because a variable defined inside a function is not automatically global; it would need an explicit 'global' declaration to be treated as global. Option B is wrong because built-in scope refers to names like 'print' or 'len' that are pre-defined in Python's builtins module, not to user-defined variables inside a function. Option D is wrong because 'nonlocal' applies to variables in nested (enclosing) function scopes, not to a variable defined directly inside a single function.

478
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

`dict1.update(dict2)` merges `dict2` into `dict1` in-place, updating existing keys and adding new ones. Option E is correct because `{**dict1, **dict2}` uses dictionary unpacking to create a new merged dictionary, available since Python 3.5.

Exam trap

The PCEP exam often tests the version-specific availability of operators like `|` and the existence of methods like `merge()`, exploiting candidates who assume all modern syntax works in older Python versions or that methods from other languages (e.g., JavaScript's `Object.assign`) exist in Python.

479
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

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.

480
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

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.

481
MCQmedium

What is the output when the following code is executed? try: print(1/0) except ZeroDivisionError: print("Cannot divide by zero")

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

The code inside the try block attempts to divide by zero, which raises a ZeroDivisionError. The except block catches this exception and executes its print statement, outputting 'Cannot divide by zero'.

Exam trap

Python Institute often tests the distinction between an unhandled exception (crash) and a caught exception (graceful handling). In this case, the exception is caught, so the program does not crash.

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.

482
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

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

483
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

The code uses a tuple (3, 4) and a dictionary {'x': 5, 'y': 6} as arguments to the print() function. The print() function outputs each argument separated by a space, so the tuple is printed as (3, 4) and the dictionary as {'x': 5, 'y': 6}, preceded by 1 and 2. Option D correctly shows this output.

Exam trap

The PCEP exam often tests the distinction between data types in output, and the trap here is that candidates mistakenly think print() unpacks or flattens compound objects like tuples and dictionaries into individual elements, rather than printing them as single objects.

How to eliminate wrong answers

Option A is wrong because it incorrectly shows the tuple as a list [3, 4] and the dictionary as {'x': 5, 'y': 6} without the tuple parentheses, misrepresenting the data types. Option B is wrong because it shows an empty dictionary {} instead of the actual dictionary {'x': 5, 'y': 6}, omitting the key-value pairs. Option C is wrong because it flattens the tuple and dictionary into individual integers (3, 4, 5, 6), which does not happen since print() outputs the tuple and dictionary as single objects, not unpacking them.

484
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

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.

485
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

The code attempts to divide by zero on line 3, which raises a ZeroDivisionError. In Python, any division where the denominator is zero (e.g., `x / 0`) triggers this runtime exception, and the traceback points to the exact line where the division occurs.

Exam trap

The PCEP exam often tests the distinction between compile-time errors (SyntaxError) and runtime errors (like ZeroDivisionError), and candidates mistakenly choose SyntaxError because they think any error in code is a syntax problem, but the code is syntactically correct — the error only occurs when the line executes.

How to eliminate wrong answers

Option A is wrong because a NameError occurs when a variable or name is not defined, but the code does not reference any undefined names — the error is a division by zero. Option B is wrong because a SyntaxError is raised when Python cannot parse the code due to invalid syntax, but the code is syntactically valid; the error occurs at runtime, not during parsing. Option C is wrong because ValueError occurs when a function receives an argument of the correct type but an inappropriate value (e.g., int('abc')), and there is no such operation here; also, line 0 does not exist in Python (lines are 1-indexed).

486
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
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

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

487
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

A tuple (1, 4, 3, 16, 5). Although it is a tuple, the values match the expected output of the code, so it is correct.

Why this answer

The code iterates over the list [1, 2, 3, 4, 5] and for each element, if it is even, it squares it; otherwise, it leaves it unchanged. The resulting list is [1, 4, 3, 16, 5], which matches option B.

Exam trap

The PCEP exam often tests the distinction between applying a transformation to even versus odd numbers, and candidates frequently misapply the condition or square the wrong subset.

How to eliminate wrong answers

Option A is wrong because it outputs the original list unchanged, ignoring the squaring of even numbers. Option C is wrong because it incorrectly squares odd numbers instead of even numbers. Option D is wrong because it squares every element, regardless of whether it is even or odd.

488
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

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.

489
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

The correct matches are: Module is a single file; Package is a directory of modules; Class is a blueprint; Function is reusable code. Common mistakes are confusing module and package definitions.

490
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 C are correct
C.for i in range(len(items)): print(i, items[i])
D.for item in items: print(items.index(item), item)
AnswerB

Incorrect. This option is a meta-statement, not a code snippet. The question asks for the correct code snippet, so it does not qualify.

Why this answer

Both Option A and Option C are valid code snippets that correctly print the index and value of each item in the list. Option A uses the clean, Pythonic enumerate() function. Option C uses range(len(items)) to iterate by index.

Since both are correct, the best answer is B, which correctly identifies that both A and C are correct. Option D is incorrect because items.index(item) can fail with duplicate values and is inefficient.

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.

491
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

The correct way to determine the number of elements in a tuple in Python is to use the built-in `len()` function, which returns the length (number of items) of any sequence or collection, including tuples. Option C is correct because `len(t)` directly gives the count of elements in tuple `t`.

Exam trap

The PCEP exam often tests the immutability of tuples by presenting list-specific methods (like `append`, `pop`, or item assignment) as distractors, knowing that candidates may confuse tuples with lists.

How to eliminate wrong answers

Option A is wrong because `t.append(5)` attempts to call the `append()` method, which is available for lists but not for tuples; tuples are immutable and do not have an `append()` method, so this would raise an AttributeError. Option B is wrong because `t[0] = 5` tries to assign a new value to an index of a tuple, which is not allowed since tuples are immutable; this would raise a TypeError. Option D is wrong because `t.pop()` attempts to call the `pop()` method, which is available for lists but not for tuples; tuples are immutable and do not have a `pop()` method, so this would raise an AttributeError.

492
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

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

The PCEP exam 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.

493
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).

494
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

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.

495
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

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.

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

497
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

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

The PCEP exam 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.

498
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