Courseiva

CCNA Computer Programming and Python Fundamentals Questions

74 of 122 questions · Page 1/2 · Computer Programming and Python Fundamentals · Answers revealed

1
MCQhard

You are a junior developer at a logistics company. Your team maintains a Python script that processes daily shipment data from a CSV file. The script reads the file, computes total weight per shipment, and writes results to a new CSV. Recently, the script started crashing sporadically with a 'ValueError: invalid literal for int() with base 10: 'NULL''. The CSV file sometimes contains the string 'NULL' in the weight column for missing values. The current code reads the weight column as: weight = int(row['weight']). Your team lead wants a robust fix that handles missing data gracefully without crashing, and also logs the line number for any problematic rows for later review. Which of the following approaches best meets these requirements?

A.Use the string method .isdigit(): if row['weight'].isdigit(): weight = int(row['weight']); else: weight = 0; no logging.
B.Read the entire file into a list, then use a list comprehension to convert weights: weights = [int(w) if w != 'NULL' else 0 for w in rows] without logging.
C.Wrap the int conversion in a try-except block: try: weight = int(row['weight']); except ValueError: weight = 0; log the line number using a counter variable.
D.Add a check: if row['weight'] != 'NULL': weight = int(row['weight']); else: weight = 0; and log a warning. Do not use try-except.
AnswerC

Catching ValueError around int() lets the script substitute a default weight for 'NULL' entries and continue processing, while a counter tracks the offending line for later review. This satisfies both the graceful-handling and line-logging constraints without halting the whole run.

Why this answer

It uses a try-except block to catch the ValueError when int() fails on 'NULL', sets weight to 0 as a fallback, and logs the line number using a counter variable. This approach handles any unexpected non-numeric string (not just 'NULL'), making it robust against future data anomalies, and satisfies the requirement to log problematic rows for review.

Exam trap

The PCEP exam often tests the distinction between LBYL (Look Before You Leap) and EAFP (Easier to Ask for Forgiveness than Permission) paradigms, and the trap here is that candidates choose a seemingly simple string check (like Option D) without realizing it fails for any unexpected invalid input, while the try-except approach is the recommended Pythonic solution for robust error handling.

How to eliminate wrong answers

Option A is wrong because .isdigit() returns False for negative numbers, floats, and empty strings, and it does not log the line number, failing the logging requirement. Option B is wrong because reading the entire file into a list and using a list comprehension without logging ignores the requirement to log line numbers for problematic rows, and it assumes all non-'NULL' values are valid integers, which is not guaranteed. Option D is wrong because it only checks for the literal string 'NULL', missing other invalid literals like empty strings or 'N/A', and while it logs a warning, it does not use a counter variable to log the specific line number as required.

2
MCQmedium

A program uses a for loop to double each element in a list: numbers = [1, 2, 3, 4, 5]; for num in numbers: num = num * 2. After execution, numbers remains unchanged. Why?

A.Reassigning num does not modify the original list element; you need to modify via index.
B.The assignment creates a new list, leaving the original unchanged.
C.Lists are immutable; their elements cannot be changed.
D.The variable num is a copy of the list element.
AnswerA

Reassigning `num` only rebinds the loop variable to a new integer object; it never writes back into the list. Integers are immutable, so no in-place mutation occurs. The stem's constraint — doubling every element — requires indexed assignment, such as `numbers[i] = numbers[i] * 2`, to alter the list itself.

Why this answer

In Python, the loop variable `num` is a reference to each element in the list, but reassigning `num` (e.g., `num = num * 2`) merely rebinds the local variable to a new integer object; it does not modify the original list element. To change the list in place, you must access elements by their index, such as `numbers[i] = numbers[i] * 2`.

Exam trap

The PCEP exam often tests the misconception that the loop variable is a mutable alias for the list element, leading candidates to believe reassigning it will update the list, when in fact it only rebinds the local variable.

How to eliminate wrong answers

Option B is wrong because the assignment `num = num * 2` does not create a new list; it only rebinds the loop variable to a new integer, leaving the original list object untouched. Option C is wrong because lists in Python are mutable; their elements can be changed via index assignment, unlike tuples or strings which are immutable. Option D is wrong because `num` is not a copy of the list element; it is a reference to the same object, but integers are immutable, so reassignment creates a new object without affecting the list.

3
Drag & Dropmedium

Arrange the steps to read data from a text file in Python.

Drag or tap steps into the slots.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

The correct sequence for reading data from a text file in Python is: first open the file using the open() function, then read its contents (e.g., with read() or readlines()), process the data as needed, and finally close the file with close(). Opening establishes a file handle, reading retrieves the data, processing uses it, and closing releases resources. Common mistakes include closing before processing, processing before reading, or reading before opening.

4
MCQmedium

What does the following code print? text = 'Hello World'; print(text.replace('o', '0').upper())

A.hell0 w0rld
B.HELLO WORLD
C.HELL0 W0RLD
D.Hell0 W0rld
AnswerC

The `replace('o', '0')` method call runs first, swapping every lowercase 'o' for a zero, producing 'Hell0 W0rld'. The chained `.upper()` then converts all remaining characters to uppercase, yielding 'HELL0 W0RLD'. This satisfies the stem's requirement to print the transformed string, with digits unaffected by uppercasing.

Why this answer

The code first replaces all occurrences of 'o' with '0' in 'Hello World', resulting in 'Hell0 W0rld'. Then it applies the .upper() method, converting all characters to uppercase, yielding 'HELL0 W0RLD'. Therefore, the output is 'HELL0 W0RLD'.

Exam trap

PCEP often tests method chaining and the order of operations; candidates may forget that .upper() is applied after .replace(), or they may think .upper() only capitalizes the first letter (confusing it with .capitalize()).

How to eliminate wrong answers

Option A is wrong because it shows lowercase letters and the replacement, but the .upper() method is applied after replace, so the result should be uppercase. Option B is wrong because it shows 'HELLO WORLD' without the replacement of 'o' with '0'; the replace method changes the 'o's to '0's before uppercasing. Option D is wrong because it shows only the first letter capitalized, but .upper() converts the entire string to uppercase, not just the first character.

5
MCQmedium

You are a developer in a company that runs a Python script daily to generate reports. The script uses the os module to list files in a directory and process each. Recently, after a server migration, the script fails with 'PermissionError: [Errno 13] Permission denied'. The script runs under a service account that has read/write access to most folders, but the migration changed the permissions on certain subdirectories. The error is intermittent, occurring only for some files. You need to fix the script to continue processing other files even if one fails. Which approach should you take?

A.Use a try-except block inside the loop to catch PermissionError for each file and continue.
B.Wrap the entire processing loop in a try-except that catches all exceptions and passes silently.
C.Before processing each file, use os.access() to check permissions and skip if not accessible.
D.Ask the server administrator to grant full permissions to the service account on all directories.
AnswerA

Wrapping each file operation in try-except catches PermissionError per iteration, so the loop continues processing remaining files instead of aborting. This satisfies the stem's requirement to handle intermittent permission failures on certain subdirectories while still processing the rest.

Why this answer

By placing a try-except block inside the loop that catches PermissionError specifically, the script can skip the problematic file and continue processing the remaining files. This approach handles the intermittent permission errors gracefully without halting the entire script. Option B is wrong because catching all exceptions silently would mask other critical errors (e.g., bugs in the processing logic).

Option C is wrong because os.access() checks may not fully reflect actual runtime permissions due to race conditions and platform-specific behavior, and it requires additional calls that could still fail. Option D is wrong because it relies on external action and does not address the need for the script to be resilient to such errors.

6
MCQeasy

Refer to the exhibit. What is the most likely cause of this error?

A.Variable x is a string
B.Variable x is used before assignment
C.Variable x is an integer
D.Variable x is misspelled
AnswerB

Python raises UnboundLocalError when a name is assigned somewhere in a function, making it local throughout, yet read before that assignment executes. The traceback points to a read of x occurring before its first assignment on that code path.

Why this answer

The error message indicates that variable 'x' is being referenced before it has been assigned a value. In Python, using a variable that has not been defined yet raises a NameError. Option B correctly identifies this as the cause.

Exam trap

The PCEP exam often tests the distinction between a variable being undefined versus being of a certain type, tricking candidates into thinking the error is about type mismatch when it is actually about the variable not existing yet.

How to eliminate wrong answers

Option A is wrong because if x were a string, it would have been assigned a value (e.g., x = 'hello'), and no NameError would occur. Option C is wrong because if x were an integer, it would also have been assigned a value (e.g., x = 5), and no NameError would occur. Option D is wrong because a misspelled variable name would still raise a NameError, but the error message would reference the misspelled name, not 'x' — the question states the error is about variable x, so misspelling is not the issue.

7
MCQhard

A programmer needs a constant that identifies the maximum number of retry attempts for a network operation. The value must not change while the program runs. Which statement about naming and using this constant in Python is accurate?

A.Assigning it inside a function makes it permanently immutable
B.Naming it MAX_RETRIES signals by convention that it should not be reassigned
C.Wrapping the value in a tuple prevents any later change to the name
D.Declaring the name with the const keyword prevents reassignment
AnswerB

Python style guidance reserves all-uppercase names with underscores for constants, communicating intent to other developers. The interpreter does not enforce this, so reassignment remains technically possible, but the naming convention is the accepted way to mark a value as fixed. Tools and reviewers rely on this signal when reading code.

Why this answer

Python relies on naming conventions rather than keywords to express constants, and an all-uppercase identifier such as MAX_RETRIES is the standard signal that a value is intended to remain fixed. The language does not block reassignment, so the guarantee is social and stylistic, supported by linters and code review. Placing values in functions or containers changes scope or internal mutability but never prevents rebinding the name.

Exam trap

The trap here is expecting Python to enforce constants through a keyword or container, when only an uppercase naming convention communicates that intent.

8
Multi-Selecthard

Which two of the following are true about Python lists? (Choose two.)

Select 2 answers
A.Lists can contain elements of different data types.
B.Lists can be used as dictionary keys.
C.Lists are indexed starting from 1.
D.Lists are immutable.
E.The len() function returns the number of elements.
AnswersA, E

Python lists are heterogeneous: a single list may hold integers, strings, floats and even nested lists together, because elements are references without a declared type. This satisfies the statement that lists accept elements of differing data types.

Why this answer

Option A is correct because Python lists are heterogeneous ordered collections, so a single list may hold elements of different data types (e.g., [1, 'two', 3.0, True]) without any type restriction. Option E is correct because the built-in len() function returns the number of elements in a list, such as len([10, 20, 30]) returning 3. Option B is incorrect because lists are mutable and therefore unhashable, so they cannot be used as dictionary keys (a TypeError is raised).

Option C is incorrect because Python uses zero-based indexing, so the first element is at index 0, not 1. Option D is incorrect because lists are mutable: elements can be added, removed, or reassigned in place via methods like append(), remove(), or item assignment.

Exam trap

The traps here include confusing list mutability with immutability, assuming indexing starts from 1, and mistakenly believing lists can be used as dictionary keys.

9
MCQmedium

What does the following code output? for i in range(3): if i == 1: continue; print(i, end=' ')

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

`range(3)` yields 0, 1, 2. When `i` equals 1, `continue` skips the remaining loop body, so `print` never runs for that iteration. Values 0 and 2 are printed with a trailing space, producing `0 2`.

Why this answer

The for loop iterates over range(3), which produces values 0, 1, and 2. When i equals 1, the continue statement skips the rest of the loop body for that iteration, so print(i, end=' ') is not executed for i=1. Thus, only 0 and 2 are printed, separated by a space, giving output '0 2'.

Option B is correct.

Exam trap

The PCEP exam often tests the continue statement by having candidates forget that it skips the rest of the loop body for the current iteration, leading them to incorrectly include the skipped value in the output.

How to eliminate wrong answers

Option A is wrong because it suggests only 1 is printed, but the continue statement skips the print for i=1, so 1 is never output. Option C is wrong because it includes 1, which is skipped by the continue statement; the loop does not print all three values. Option D is wrong because it omits 2; the loop continues after the continue and prints 2 when i=2.

10
MCQhard

Consider code: def outer(): x = 1 def inner(): nonlocal x x = 2 inner() print(x) outer() What is printed?

A.2
B.1
C.Error
D.None
AnswerA

The `nonlocal x` declaration binds `inner`'s assignment to the enclosing `outer` function's variable, not a new local one. So `x = 2` mutates the same cell that `print(x)` reads after `inner()` returns, satisfying the stem's requirement that the enclosing scope's value be updated. Output is 2.

Why this answer

The `nonlocal` declaration inside `inner()` binds the variable `x` to the `x` defined in the enclosing `outer()` function. When `inner()` assigns `x = 2`, it modifies that outer `x`, so after `inner()` returns, `print(x)` in `outer()` outputs 2.

Exam trap

The PCEP exam often tests the distinction between `nonlocal` and `global`, and the trap here is that candidates mistakenly think `nonlocal` is unnecessary or causes an error, or they assume the inner assignment creates a separate local variable that does not affect the outer scope.

How to eliminate wrong answers

Option B is wrong because it assumes `inner()` creates a separate local variable `x` without `nonlocal`, but the `nonlocal` keyword explicitly links `x` to the enclosing scope, so the assignment overwrites the outer `x` from 1 to 2. Option C is wrong because `nonlocal x` is valid in a nested function when `x` exists in an enclosing (but non-global) scope; no `SyntaxError` or `NameError` occurs. Option D is wrong because `print(x)` executes and outputs an integer value, not `None`; `None` would only appear if `print` had no argument or the function returned `None` explicitly.

11
MCQmedium

A junior developer is writing a script to process a list of user IDs: ids = [101, 102, 103, 104]. The goal is to create a new list where each ID is increased by 10, without modifying the original list. The developer writes: new_ids = ids.append(10). However, the output shows None. The developer needs to correctly create the new list. Which code should the developer use to achieve this?

A.new_ids = [id + 10 for id in ids]
B.for i in range(len(ids)): ids[i] += 10; new_ids = ids
C.new_ids = ids + 10
D.new_ids = map(lambda x: x+10, ids)
AnswerA

A list comprehension builds a new list by evaluating id + 10 for each element, leaving ids untouched. The append method returns None and mutates in place, so it cannot satisfy the requirement of a separate transformed list.

Why this answer

It uses a list comprehension to create a new list by adding 10 to each element of the original list `ids`, leaving the original list unchanged. The `append()` method modifies the list in place and returns `None`, which is why the developer got `None`.

Exam trap

Python Institute often tests the distinction between methods that modify a list in place and return `None` (like `append()`, `sort()`) versus those that return a new object (like list comprehensions or `sorted()`), leading candidates to mistakenly assign the result of `append()` to a variable.

How to eliminate wrong answers

Option B is wrong because it modifies the original list `ids` in place (using `ids[i] += 10`) and then assigns the same list object to `new_ids`, so the original list is altered. Option C is wrong because `ids + 10` attempts to add an integer to a list, which raises a `TypeError` in Python (lists can only be concatenated with other lists). Option D is wrong because `map()` returns a map object (an iterator), not a list; to get a list, it must be wrapped in `list()`, e.g., `list(map(...))`.

12
MCQeasy

A developer writes code to calculate the area of a rectangle and prints it. The code is: length = 10 width = 5 area = length + width print('The area is', area) If the width is accidentally assigned a string '5', what error will occur?

A.ValueError
B.SyntaxError
C.TypeError
D.NameError
AnswerC

Assigning `'5'` makes `width` a string, so `length + width` attempts to add an integer and a string. Python does not implicitly coerce operands across these types, so the addition raises a TypeError before `print` runs. This satisfies the stem's scenario of accidental string assignment, where the failure occurs at the arithmetic operation itself.

Why this answer

In Python, adding an integer and a string is not a valid operation; it will raise a TypeError because Python cannot implicitly convert the string to an integer for arithmetic. Therefore, the code will raise a TypeError when executed.

Exam trap

The trap is that candidates may incorrectly assume that Python allows integer + string for arithmetic addition, but actually it raises a TypeError. The key is to recognize that Python does not perform implicit type conversion in this context.

How to eliminate wrong answers

Option A is wrong because ValueError is raised when a function receives an argument of the correct type but an inappropriate value (e.g., int('abc')), not for type mismatches in arithmetic. Option B is wrong because SyntaxError occurs when the Python parser encounters invalid syntax before execution, such as missing colons or unmatched parentheses; the code here is syntactically valid. Option D is wrong because NameError occurs when a variable name is not defined; both length and width are defined, so no NameError is raised.

13
Multi-Selecthard

A developer is writing a Python script and needs to create valid variable names. Which two of the following are valid variable names? (Choose two.)

Select 2 answers
A.2ndPlace
B.total_amount
C.my-var
D.for
E._value
AnswersB, E

total_amount uses only letters and an underscore, and does not start with a digit. It is a valid Python identifier. Underscores are commonly used to separate words in variable names, and this name follows all the rules for valid identifiers.

Why this answer

Valid Python identifiers must start with a letter or underscore, followed by letters, digits, or underscores, and cannot be keywords. _value and total_amount satisfy these rules, while my-var contains a hyphen, 2ndPlace starts with a digit, and for is a keyword.

Exam trap

The trap here is assuming that any name without spaces is valid, but identifiers cannot contain hyphens, start with digits, or be reserved keywords.

14
MCQeasy

A programmer wants to iterate over a list of strings and print each string in uppercase. Which of the following code snippets will accomplish this?

A.for item in my_list: print(item.upper)
B.for item in my_list: item.upper() print(item)
C.for i in my_list: print(my_list[i].upper())
D.for item in my_list: print(item.upper())
AnswerD

Iterating directly over my_list yields each string, and calling .upper() on it returns the uppercase form, which print outputs. This satisfies the requirement to print every string in uppercase without needing index tracking or a separate conversion step.

Why this answer

It correctly calls the `upper()` method on each string `item` in the list `my_list` and prints the result. The `upper()` method returns a new string with all characters converted to uppercase, and the `print()` function outputs that value to the console.

Exam trap

The trap here is that candidates often forget to include parentheses when calling a method (e.g., `item.upper` vs `item.upper()`), or they mistakenly think `upper()` modifies the string in place, leading them to print the original variable instead of the returned value.

How to eliminate wrong answers

Option A is wrong because `item.upper` without parentheses does not call the method; it merely references the method object, so nothing is printed. Option B is wrong because `item.upper()` returns a new string but does not modify `item` in place, and the subsequent `print(item)` prints the original lowercase string, not the uppercase version. Option C is wrong because `my_list[i]` attempts to use an integer index `i` as a list index, but `i` is a string from the list, not an integer; this will raise a `TypeError`.

15
Multi-Selectmedium

A trainee is reviewing how Python 3 handles basic data types and type conversion in a small inventory script. Which TWO statements about Python's built-in numeric and string types are correct? (Choose two.)

Select 2 answers
A.Calling int('42') returns the integer 42, while int('4.2') raises a ValueError
B.The bool type is a distinct numeric type where True equals 1 and False equals 0 in arithmetic
C.The str type is mutable, so individual characters can be replaced by index assignment
D.The int type can represent arbitrarily large whole numbers limited only by available memory
E.The float type stores decimal values with exact precision for any fractional number
AnswersA, D

int accepts a string containing digits and optional sign, converting it to the matching integer. A string with a decimal point is not a valid integer literal, so conversion fails with ValueError. The correct path for such input is float('4.2') followed by int() if truncation is desired, making this statement an accurate description of the behaviour.

Why this answer

Python 3 integers grow to whatever size memory allows, so counters never silently overflow, and int() accepts only strings that look like whole numbers, rejecting anything with a decimal point. Together these behaviours shape how inventory quantities and parsed input are handled. Floats remain binary approximations, strings stay immutable, and bool is a subclass of int rather than a separate numeric family.

Exam trap

The trap here is assuming floats store decimal values exactly and that bool sits outside the integer hierarchy, when both assumptions contradict Python's actual type model.

16
MCQeasy

A beginner writes: x = 10; y = 3; print(x // y). What is the output?

A.3
B.1
C.3.0
D.3.333
AnswerA

The // operator performs floor division, discarding the fractional part and rounding toward negative infinity. With 10 divided by 3, the true quotient is 3.333..., so floor division returns the integer 3, not 3.33 or 4.

Why this answer

The // operator in Python performs floor division, which returns the largest integer less than or equal to the result of the division. Since 10 divided by 3 equals 3.333..., the floor of that value is 3, and because both operands are integers, the result is an integer (3), not a float.

Exam trap

The PCEP exam often tests the distinction between floor division (//) and true division (/) by using integer operands, leading candidates to mistakenly expect a float result or to confuse floor division with truncation toward zero.

How to eliminate wrong answers

Option B is wrong because 1 would be the result of the modulo operation (10 % 3), not floor division. Option C is wrong because floor division with two integers returns an integer, not a float; 3.0 would require at least one operand to be a float (e.g., 10 // 3.0). Option D is wrong because 3.333 is the result of true division (10 / 3), not floor division.

17
Multi-Selecthard

Which THREE of the following are correct ways to create a list containing the numbers 1, 2, 3? (Choose three.)

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

range(1,4) yields 1, 2 and 3, stopping before the exclusive upper bound. The comprehension collects each value into a new list, producing [1, 2, 3] with the correct integers in ascending order, satisfying the question's requirement.

Why this answer

Option A, `[x for x in range(1,4)]`, is correct because a list comprehension over `range(1,4)` iterates x = 1, 2, 3 (the stop value 4 is exclusive) and builds a list `[1, 2, 3]`. Option C, `list((1, 2, 3))`, is correct because the `list()` constructor converts the tuple `(1, 2, 3)` into a new list containing those same elements. Option D, `[1, 2, 3]`, is correct because it is a direct list literal that already contains the numbers 1, 2, and 3.

Option B, `(1, 2, 3)`, does not belong because parentheses create a tuple, not a list. Option E, `{1, 2, 3}`, does not belong because curly braces create a set, which is unordered and not a list.

Exam trap

The PCEP exam often tests the distinction between list literals (`[]`), tuple literals (`()`), and set literals (`{}`), trapping candidates who confuse the syntax for these different data structures.

18
MCQeasy

A Python program contains the following code: print(10 / 4) What is displayed when this program runs?

A.2
B.2.0
C.A TypeError is raised.
D.2.5
AnswerD

The division operator / always performs true division in Python 3, even when both operands are integers, and returns a float. Dividing 10 by 4 yields 2.5, so 2.5 is printed. This differs from some other languages where integer division truncates the result, but Python 3 deliberately returns the exact quotient as a float.

Why this answer

In Python 3, the single forward slash performs true division regardless of operand types, so 10 / 4 evaluates to the float 2.5. Floor division with // would instead produce 2, and integer truncation does not happen with /. The print function then displays that float value on the console.

Exam trap

The trap here is assuming Python 3 behaves like languages where dividing two integers discards the remainder, when the / operator actually returns a float.

19
MCQhard

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

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

A list comprehension collapses the loop, condition, and append into one expression, producing the same filtered names list. It is the idiomatic Python replacement, satisfying the senior developer's request for conciseness while preserving identical behaviour and output.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

20
Multi-Selecthard

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

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

Tuples cannot be changed after creation.

Why this answer

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

Exam trap

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

21
MCQmedium

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

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

enumerate() yields index-value pairs directly, avoiding manual counter maintenance or range(len(items)) indexing. It satisfies the requirement to print both the index and its corresponding value in one clean iteration, which is the idiomatic and most readable construct for this task.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

22
MCQeasy

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

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

Operator precedence makes division bind tighter than addition, so Python evaluates c / 3 as 30 / 3 = 10.0, then adds a + b, giving 10 + 20 + 10.0 = 40.0. The float result from true division explains the decimal output.

Why this answer

Operator precedence in Python dictates that division (/) has higher precedence than addition (+). Therefore, the expression `a + b + c / 3` is evaluated as `a + b + (c / 3)`, which is `10 + 20 + (30 / 3) = 10 + 20 + 10.0 = 40.0`. The result is a float because division always returns a float in Python 3.

Exam trap

The PCEP exam often tests operator precedence by presenting an expression without parentheses, leading candidates to incorrectly assume left-to-right evaluation or to compute the average as `(a + b + c) / 3` instead of `a + b + (c / 3)`.

How to eliminate wrong answers

Option A is wrong because it assumes the entire sum is divided by 3 (i.e., `(a + b + c) / 3 = 60 / 3 = 20.0`), not 60.0. Option B is wrong because it represents the result of `(a + b + c) / 3 = 20.0`, which ignores operator precedence. Option D is wrong because it might come from incorrectly computing `c / 3 = 10.0` and then adding only `a` (10 + 10.0 = 20.0) or from a different miscalculation, but it does not match the correct evaluation.

23
Multi-Selecthard

A developer is reviewing how literals and operators behave in a Python script. Which TWO of the following statements about Python literals and operators are true? (Choose two.)

Select 2 answers
A.The expression 3 * 'ab' evaluates to 'ababab'.
B.The literal None is the same as the integer 0.
C.The expression 2 ** 3 evaluates to 6.
D.The expression '5' + 5 evaluates to the string '55'.
E.The literal True is equivalent to the integer 1 in arithmetic expressions.
AnswersA, E

Python allows a string to be multiplied by an integer, which repeats the string that many times. Multiplying 'ab' by 3 concatenates three copies, producing 'ababab'. This is a deliberate language feature for sequence repetition and works with lists and tuples as well, so the statement accurately describes valid Python behavior.

Why this answer

String repetition with * and the numeric nature of bool are both real Python behaviors: multiplying a string by an integer repeats it, and True acts as 1 in arithmetic because bool subclasses int. Mixing str and int with + raises TypeError, None is not numerically zero, and ** performs exponentiation, so only the repetition and boolean-arithmetic statements hold.

Exam trap

The trap here is assuming Python silently coerces between strings and numbers, when mixed-type addition actually raises TypeError.

24
MCQhard

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

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

Mutating each dictionary in place adds a `processed` key to the caller's own objects, so the original list's elements change despite the function returning `data`. This violates the stated requirement that the original list remain unchanged. To avoid the side effect, build and return new dictionaries instead of editing the passed-in ones.

Why this answer

The function mutates the dictionaries in the original list by adding the key 'processed' to each one. This violates the principle of avoiding side effects in functions, as the caller's data is changed unexpectedly. In Python, dictionaries are mutable objects, so modifying them inside a function affects the original list elements.

Exam trap

The PCEP exam often tests the distinction between modifying a list's structure (e.g., append, remove) and modifying the mutable objects the list contains, leading candidates to overlook that mutating dictionary items is still a side effect on the original data.

How to eliminate wrong answers

Option A is wrong because PEP 8 recommends 4 spaces per indentation level, not 2; the code uses 4 spaces, which is correct. Option B is wrong because a list comprehension cannot directly mutate dictionaries in place; it would create a new list, not modify the original items as intended. Option C is wrong because while returning a value without using it is syntactically acceptable, the core issue is the unintended modification of the original data, not the return value usage.

25
MCQhard

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

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

Dictionary keys must be hashable, and lists are mutable, so Python raises TypeError: unhashable type: 'list' when a list is used as a key. Tuples, strings and integers are hashable and would work, but a list cannot be hashed.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

26
MCQmedium

A developer writes a short script to convert a numeric string entered at the console into a number for arithmetic: value = input('Enter a quantity: ') total = value * 2 print(total) A user types 7 and presses Enter. What is printed, and why?

A.14, because input converts the entry to an integer automatically
B.7, because the second operand is ignored for string values
C.77, because the string '7' is repeated twice by the * operator
D.A TypeError is raised, because a string cannot be multiplied
AnswerC

input returns the str '7'. The * operator applied to a str and an int performs repetition rather than multiplication, producing a new string containing the original text twice. The result is the two-character string '77', which print displays. Explicit conversion with int() would be required for numeric doubling.

Why this answer

The built-in input always yields a str in Python 3, so value refers to the two-character sequence '7'. When * receives a str on the left and an int on the right, it repeats the string that many times instead of multiplying numerically. The assignment therefore stores '77', and print outputs those characters.

Converting with int(value) first would give the arithmetic result 14.

Exam trap

The trap here is assuming input returns a number when the user types digits, when it actually returns a string that triggers repetition with the * operator.

27
MCQhard

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

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

Iterating line by line with try-except isolates each conversion, so 'Absent' and blank lines raise ValueError and are skipped rather than poisoning the whole list, which is what produced NaN. The skip counter satisfies the professor's requirement to warn about ignored lines, and the average is computed only from valid floats.

Why this answer

It uses a try-except block to safely attempt conversion of each line to float, incrementing a skip counter for lines that fail (e.g., 'Absent' or blank). After processing, it computes the average only from successfully converted scores and prints both the average and the number of skipped lines, meeting the professor's requirements exactly.

Exam trap

The PCEP exam often tests the misconception that `isdigit()` or simple string emptiness checks are sufficient for numeric validation, but they fail for floats, negative numbers, or non-numeric text like 'Absent'.

How to eliminate wrong answers

Option A is wrong because filtering with a lambda that checks if a line can be converted to int would reject valid float values (e.g., '85.5') and also does not handle blank lines or provide a warning count. Option C is wrong because the condition `if line.strip() != ''` only skips blank lines but does not handle non-numeric strings like 'Absent', causing a ValueError when float() is called. Option D is wrong because `isdigit()` returns False for strings with decimal points (e.g., '85.5') and negative signs, so it would incorrectly skip valid float scores, and it also does not count skipped lines.

28
MCQeasy

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

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

Returning the area rather than printing it lets callers capture the value in a variable and feed it into further calculations, satisfying the stem's requirement for reusability and composability. Printing only emits output to stdout, leaving no usable value for subsequent computation.

Why this answer

Returning a value from a function allows the caller to capture and reuse that value in subsequent calculations, making the function composable and reusable. Printing the result inside the function (as in the original code) only outputs it to the console and discards the value, preventing further programmatic use. By modifying the function to return the area, the developer can assign the result to a variable and use it in other expressions.

Exam trap

The PCEP exam often tests the distinction between printing a value and returning a value, exploiting the common beginner misconception that printing makes the value available for later use in code.

How to eliminate wrong answers

Option A is wrong because storing the area in a global variable introduces side effects, reduces modularity, and can lead to maintenance issues such as unintended overwrites or difficulty tracking state changes. Option C is wrong because keeping the function as is (printing the result) means the area value is not available to the calling code; calling it from another function still only prints the area, not returns it. Option D is wrong because print is a function that outputs to stdout and returns None; passing the area as an argument to print does not make the area available for computation—it merely displays it.

29
MCQmedium

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

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

With a = 5 and b = 10, the comparison a > b evaluates to False, and the not operator inverts that to True. This satisfies the logical expression's requirement of producing a True result.

Why this answer

Given a = 5 and b = 10, the expression not (a > b) evaluates the inner comparison a > b, which is 5 > 10 = False, and then applies not, yielding True. This is the only option that evaluates to True with the given values. Understanding operator precedence and boolean negation is essential for PCEP-style questions.

Exam trap

PCEP often tests operator precedence and De Morgan's laws, tricking candidates who mis-evaluate not (a > b) as (not a) > b or who confuse the negation of a comparison with the comparison of a negation.

How to eliminate wrong answers

Option A is wrong because a > b is False (5 > 10 is false) and b < 0 is False (10 < 0 is false); False and False evaluates to False. Option B is wrong because not (a < b) evaluates a < b as True (5 < 10), and not True is False. Option D is wrong because a == b is False (5 ≠ 10) and False or False evaluates to False.

30
MCQeasy

A developer writes the following code: x = 5 if x > 3: print('A') else: print('B') print('C') What is the output?

A.A B C
B.B C
C.A
D.A C
AnswerD

Since x is 5, the condition x > 3 is True, so the if block prints 'A'. The else block is skipped. After the if-else structure, the indented level returns to the top, so print('C') runs unconditionally, producing 'A' then 'C' on separate lines.

Why this answer

With x equal to 5, the condition x > 3 is True, so the if block prints 'A' and the else block is skipped. The final print('C') is outside the conditional structure and always executes. The output is therefore 'A' followed by 'C' on separate lines.

Exam trap

The trap here is assuming that all indented lines run or that the else always executes, when in fact only one branch of an if-else runs and the trailing print is unconditional.

31
Multi-Selecteasy

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

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

'total_sum' is valid because it begins with a letter and contains only letters, digits, and underscores, with no spaces or leading digit. Python identifiers are case-sensitive and cannot be keywords, all of which this name satisfies.

Why this answer

Option C (total_sum) is valid because Python identifiers may contain letters, digits, and underscores, and this name starts with a letter and uses only those allowed characters. Option E (_count) is valid because a leading underscore is permitted in Python identifiers, and the rest of the name contains only letters. Option A (my-var) is invalid because the hyphen is not allowed in Python identifiers; it is interpreted as a subtraction operator.

Option B (2nd_place) is invalid because identifiers cannot begin with a digit. Option D (for) is invalid because 'for' is a reserved Python keyword and cannot be used as a variable name.

Exam trap

The PCEP exam often tests the rule that hyphens are invalid in variable names (tricking candidates who are used to languages like Lisp or CSS) and that keywords cannot be used as identifiers, even though they look like valid names.

32
MCQeasy

A programmer is writing a Python script to calculate the area of a circle. They write the following code: radius = 5 area = 3.14 * radius ** 2 print(area) What is the output of this code?

A.25
B.31.4
C.An error occurs because radius is an integer and cannot be used with exponentiation.
D.78.5
AnswerD

The expression 3.14 * radius ** 2 is evaluated as 3.14 * (5 ** 2) because the exponentiation operator ** has higher precedence than multiplication. 5 ** 2 equals 25, and 3.14 * 25 equals 78.5. The print statement outputs 78.5, which is the correct area calculation using the given approximation of pi.

Why this answer

The exponentiation operator ** has higher precedence than multiplication, so radius ** 2 is computed first, yielding 25. Then 3.14 * 25 equals 78.5, which is printed. This demonstrates correct operator precedence in Python and the use of the exponentiation operator for squaring a number.

Exam trap

The trap here is misapplying operator precedence by multiplying before exponentiating, which would yield a different result.

33
Matchingmedium

Match each Python keyword to its use.

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

Concepts
Matches

Starts a conditional statement

Starts a loop over a sequence

Starts a loop that repeats while a condition is true

Defines a function

Exits a function and optionally returns a value

Why these pairings

The correct matches are: break is used to exit a loop prematurely; continue skips the current iteration; pass is a no-operation statement. Common mistakes include swapping the definitions of break and continue.

34
MCQhard

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

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

The int() call raises a ValueError because 'abc' cannot be parsed as base-10 integer, so execution jumps straight to the except block, printing the error message. The finally block then runs regardless, printing "Done". This satisfies the stem's requirement that both the error text and "Done" appear in that order.

Why this answer

The code attempts to convert the string 'abc' to an integer using int('abc'), which raises a ValueError. The except block catches this exception and prints 'Error:' followed by the exception message, then the finally block always executes and prints 'Done'. Thus, the output is 'Error: invalid literal for int() with base 10: 'abc'' followed by 'Done'.

Exam trap

The PCEP exam often tests the misconception that the finally block suppresses or replaces the exception output, or that the except block does not print the exception message, leading candidates to overlook the explicit print of the error message before 'Done'.

How to eliminate wrong answers

Option A is wrong because it suggests the message is omitted, but the except block explicitly prints the exception message via the 'as e' clause. Option B is wrong because the exception is caught by the except block, so it is handled, not unhandled. Option D is wrong because the except block executes before the finally block, so 'Error: ...' is printed before 'Done', not only 'Done'.

35
MCQmedium

A developer writes the following code and runs it without any error: x = 5 y = 2.0 z = x + y What is the value and type of z?

A.A TypeError is raised because int and float cannot be added
B.7, of type int
C.7.0, of type float
D.7.0, of type str
AnswerC

Python's arithmetic follows a numeric type hierarchy, and mixing an int with a float promotes the int to float before the operation. The addition of 5 and 2.0 therefore produces 7.0 as a float object. The type of the variable z is float, confirmed by calling type(z), which returns the float class.

Why this answer

When Python evaluates an arithmetic expression containing both an int and a float, it converts the integer to a float and produces a float result. Adding five and two point zero yields the float value seven point zero. The variable z therefore references a float object, which can be verified by examining type(z) in the interpreter.

Exam trap

The trap here is assuming the result keeps the integer type because the value looks whole, overlooking Python's automatic float promotion in mixed arithmetic.

36
MCQeasy

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

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

The built-in `input()` function always returns a string, so `num * 2` performs string repetition rather than arithmetic multiplication, producing `'55'`. Wrapping the call as `int(input("Enter a number: "))` converts the value to an integer, satisfying the requirement to double the numeric input and print `10`.

Why this answer

The `input()` function in Python always returns a string, even if the user types a number. When you use the `*` operator on a string, it repeats the string, so `'5' * 2` yields `'55'`. To perform numeric multiplication, you must convert the input to an integer using `int(input(...))`.

Exam trap

The trap here is that candidates often assume `input()` returns a number because the user typed digits, but Python treats all keyboard input as a string, and the `*` operator's string repetition behavior is a classic PCEP trick.

How to eliminate wrong answers

Option A is wrong because there is no syntax error; the line `result = num * 2` is syntactically valid Python. Option B is wrong because the `print()` function is correctly outputting the value of `result`; the issue is the value itself, not the formatting. Option C is wrong because `num` is not a built-in function name; built-in functions like `int`, `float`, `str` are reserved, but `num` is a free variable name.

37
MCQmedium

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

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

The parameter b uses its default value of 5 because only one argument is supplied, so the call evaluates 10 + 5, returning 15. Python applies default arguments when the corresponding positional argument is omitted.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

38
MCQmedium

A developer is writing a Python script and assigns a value to a variable named '2nd_place'. When the script is run, it raises a SyntaxError. What is the cause of this error?

A.Variable names must be uppercase.
B.Variable names cannot start with a digit.
C.The name '2nd_place' is a reserved keyword.
D.Variable names cannot contain underscores.
AnswerB

In Python, identifiers must begin with a letter (a-z, A-Z) or an underscore, not a digit. '2nd_place' starts with '2', which is invalid. This rule prevents ambiguity with numeric literals. The interpreter cannot parse '2nd_place' as a single token, so it raises a SyntaxError at the point of assignment.

Why this answer

Python identifiers must start with a letter or underscore, not a digit. The name '2nd_place' begins with '2', so the parser cannot treat it as a single identifier and raises a SyntaxError. Underscores are allowed, uppercase is not required, and the name is not a keyword.

Exam trap

The trap here is focusing on the underscore or the word 'place' instead of the leading digit, which is the actual syntax violation.

39
MCQeasy

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

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

A try-except around int() catches ValueError for each non-numeric field such as 'N/A' or empty strings, letting the loop skip or substitute that row and continue. This satisfies the requirement to handle bad data robustly without stopping the entire process.

Why this answer

Wrapping the conversion in a try-except block allows the script to catch the ValueError for each row individually, log or handle the problematic row (e.g., skip it or use a default value), and continue processing the remaining rows without crashing. This is the standard Pythonic approach for handling expected but unpredictable data quality issues in external input, as it separates error handling from the main logic and preserves the robustness of the batch process.

Exam trap

The PCEP exam often tests the misconception that logging or pre-processing (like regex) is sufficient to prevent runtime errors, when in fact only exception handling can gracefully recover from an exception that has already been raised.

How to eliminate wrong answers

Option B is wrong because adding logging before the conversion only prints the problematic value but does not prevent the ValueError from being raised, so the script will still crash on the first invalid row. Option C is wrong because using a regex to replace all non-digit characters (e.g., removing 'N/A' entirely) could silently corrupt data (e.g., turning '123-456' into '123456' or removing valid negative signs) and does not handle empty strings or other non-numeric formats robustly. Option D is wrong because contacting the external source is a long-term process improvement, not an immediate fix; it does not handle the current crashing script and assumes the source can always provide clean data, which is unrealistic in production.

40
MCQeasy

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

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

Building a list inside the function and returning it satisfies both constraints: it replaces printing with a returned value, and it avoids side effects by keeping all state local. Appending each qualifying name during iteration, then returning the list, gives the manager the required collection without mutating external state.

Why this answer

It modifies the function to build a list of qualifying employee names inside the function and returns that list. This avoids side effects (no global variables, no mutation of the input dictionary) and follows the principle of returning results rather than printing them, making the function reusable and testable.

Exam trap

The PCEP exam often tests the concept of side effects versus pure functions, and the trap here is that candidates may think mutating the input dictionary (Option C) or using a global variable (Option A) are acceptable, when in fact they violate the principle of avoiding side effects and reduce code maintainability.

How to eliminate wrong answers

Option A is wrong because using a global list introduces side effects and makes the function non-reentrant and harder to debug; it also violates the principle of avoiding global state. Option B is wrong because capturing stdout is a fragile workaround that does not actually return data and still relies on the function's side effect of printing; it also adds unnecessary complexity and breaks if output is redirected. Option C is wrong because using the dictionary's update method to mark bonus status mutates the original sales dictionary, which is a side effect that can cause unexpected behavior in other parts of the script and violates the requirement to avoid side effects.

41
Matchingmedium

Match each Python data type to its description.

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

Concepts
Matches

Whole numbers, e.g., 42

Numbers with decimal point, e.g., 3.14

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

Logical values True or False

Ordered, mutable collection of items

Why these pairings

The correct matches are: A (int - whole numbers), B (float - numbers with decimal point), D (bool - Boolean values True or False). Option C (str) is incorrect because strings are immutable sequences of characters, not mutable collections. Option E (list) is incorrect because lists are mutable collections, not immutable sequences.

Option F (tuple) is incorrect because tuples are immutable sequences, not mutable collections.

42
MCQeasy

A Python program needs to store the integer value 42 in a variable named count. Which line of code correctly assigns this value?

A.count == 42
B.42 = count
C.count = 42
D.count := 42
AnswerC

The single equals sign = is the assignment operator in Python. It binds the name count to the integer object 42. This is the standard and correct way to store a value in a variable, satisfying the requirement exactly.

Why this answer

The assignment operator = stores a value in a variable. In this scenario, count = 42 correctly binds the name count to the integer 42. The other options either compare, reverse the assignment, or use an operator that is not valid as a standalone statement.

Exam trap

The trap here is confusing the assignment operator = with the equality operator ==, which performs a comparison rather than storing a value.

43
Multi-Selecteasy

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

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

Passing a tuple to the `list()` constructor iterates its elements and builds a new list, yielding `[1, 2, 3]`. This satisfies the stem's requirement for a valid list-creation method, since `list()` accepts any iterable, including tuples, strings and ranges, not just list literals.

Why this answer

Option A, list((1, 2, 3)), is correct because the list() constructor accepts any iterable — here a tuple — and returns a new list object [1, 2, 3]. Option B, [x for x in range(3)], is correct because a list comprehension is a valid literal-style expression that builds a list, producing [0, 1, 2]. Option C, [1, 2, 3], is correct because it is a direct list display (literal) using square brackets, which is the most basic way to create a list.

Option D, (1, 2, 3), is not correct because parentheses with commas create a tuple, not a list. Option E, {1, 2, 3}, is not correct because curly braces create a set (or a dict if key-value pairs are used), not a list.

Exam trap

The PCEP exam often tests the distinction between list literals (`[]`), tuple literals (`()`), and set literals (`{}`), trapping candidates who confuse the syntax for creating a list with that of other sequence or collection types.

44
MCQhard

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

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

PEP 8 specifies that constants use all-uppercase letters with underscores separating words, so MAX_RETRIES matches the required naming convention for a maximum retries constant. Lowercase or camelCase forms are reserved for variables, functions and classes.

Why this answer

PEP 8 (Python Enhancement Proposal 8) recommends that constants be named using uppercase letters with underscores separating words, i.e., `MAX_RETRIES`. This convention distinguishes constants from regular variables, which use lowercase with underscores, and helps improve code readability and maintainability.

Exam trap

The PCEP exam often tests the distinction between variable naming conventions (snake_case for variables vs. UPPER_CASE for constants) and the rule that identifiers cannot start with a digit, leading candidates to confuse camelCase or invalid names with PEP 8 recommendations.

How to eliminate wrong answers

Option B is wrong because `max_retries` follows the PEP 8 naming convention for regular variables (snake_case), not constants, which should be in all uppercase. Option C is wrong because `1st_retry_limit` starts with a digit, which is invalid in Python (identifiers cannot begin with a number) and violates PEP 8 naming rules. Option D is wrong because `maxRetries` uses camelCase, which is not recommended by PEP 8 for Python code; PEP 8 specifies snake_case for variable names and UPPER_CASE for constants.

45
MCQeasy

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

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

The exponentiation operator ** binds tighter than multiplication, so radius ** 2 evaluates first, giving 25. Multiplying by 3.14 yields 78.5, which print outputs. This satisfies the stem's requirement to determine the exact value produced by the given expression.

Why this answer

78.5 because the expression `3.14 * radius ** 2` is evaluated according to Python's operator precedence: exponentiation (`**`) has higher precedence than multiplication (`*`), so `radius ** 2` computes 5 squared (25), then multiplied by 3.14 gives 78.5. The `print(area)` function outputs this value.

Exam trap

The Python Institute often tests operator precedence by embedding exponentiation in a multiplication expression, trapping candidates who mistakenly compute `(3.14 * radius) ** 2` (yielding 246.49) or who confuse area with circumference (2 * pi * r).

How to eliminate wrong answers

Option B (157.0) is wrong because it incorrectly assumes the formula uses diameter instead of radius (e.g., 3.14 * 10 ** 2 / 2 or 3.14 * 5 * 10). Option C (25.0) is wrong because it only computes `radius ** 2` and ignores multiplication by pi (3.14). Option D (31.4) is wrong because it incorrectly multiplies 3.14 by radius (5) instead of radius squared (25), effectively computing circumference (2 * pi * r) or a linear relationship.

46
MCQeasy

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

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

range(5) yields exactly five values, so the for loop body executes precisely five times without a manually managed counter. A while loop would need separate increment logic, making this construct the clearest fit for a fixed repetition count.

Why this answer

The `for i in range(5)` loop is the most idiomatic and concise way to repeat an action a fixed number of times (5 iterations) in Python. The `range(5)` generates a sequence from 0 to 4, and the loop body executes exactly 5 times, which directly matches the requirement to run a test 5 times without needing manual counter management.

Exam trap

The trap here is that candidates may confuse the `while` loop (option B) as equally valid, but the PCEP exam expects knowledge that `for` loops with `range` are the preferred and most Pythonic construct for fixed-count iteration, while `while` loops are intended for condition-based repetition where the number of iterations is not known in advance.

How to eliminate wrong answers

Option A is wrong because `do: ... while counter < 5` is not valid Python syntax; Python does not have a `do-while` loop construct (it uses `while` with a condition checked before each iteration). Option B is wrong because although it uses a valid `while` loop, it requires explicit initialization of `counter` before the loop and manual increment (`counter += 1`) inside the loop, making it less concise and more error-prone than the `for` loop for a fixed number of iterations. Option D is wrong because `def repeat(): ... repeat()` defines a recursive function that calls itself, which would cause infinite recursion (and a `RecursionError`) unless a base case is added; it is not a loop construct and is inappropriate for repeating a test exactly 5 times.

47
MCQhard

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

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

Replacing `iteritems()` with `items()` restores iteration over the dictionary's key–value pairs, satisfying the Python 3 requirement that the legacy call be updated. Python 3 removed `iteritems()` entirely, and `items()` now returns a view object rather than a list, so the minimal edit resolves the `AttributeError` without restructuring the surrounding loop.

Why this answer

In Python 3, the `dict.iteritems()` method was removed because `dict.items()` now returns a view object that provides lazy iteration, similar to what `iteritems()` did in Python 2. Replacing `iteritems()` with `items()` is the minimal change that preserves the iteration behavior and works correctly in Python 3.

Exam trap

The PCEP exam often tests the misconception that Python 3 requires an external library or a different method name to achieve the same iteration behavior, when in fact `items()` alone is the correct and minimal replacement for `iteritems()`.

How to eliminate wrong answers

Option A is wrong because `viewitems()` does not exist in Python 3; it was a Python 2 method on dictionary views that is not available in Python 3. Option B is wrong because `iteritems()` from the `six` compatibility library would require adding an external dependency and is not a minimal change; the standard library already provides `items()` for the same purpose. Option D is wrong because converting the dictionary to a list of tuples is unnecessary and inefficient, as `items()` already provides the needed iteration without creating an intermediate list.

48
MCQmedium

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

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

Combining `num > 0` with `num % 2 == 0` using `and` requires both conditions to hold simultaneously, correctly identifying positive even numbers. The modulo operator returns zero only for even values, while the comparison excludes zero and negatives, satisfying the stem's dual constraint in one expression.

Why this answer

Python uses the keyword `and` for logical conjunction, and the equality operator is `==` (not `=`). The expression `num > 0 and num % 2 == 0` correctly checks that `num` is both greater than zero and divisible by 2 with no remainder, which defines a positive even number.

Exam trap

The PCEP exam often tests the distinction between logical operators (`and`, `or`) and bitwise operators (`&`, `|`), as well as the difference between assignment (`=`) and comparison (`==`), to catch candidates who confuse syntax from other programming languages.

How to eliminate wrong answers

Option A is wrong because `&` is the bitwise AND operator in Python, not the logical AND; it would perform a bitwise operation on the boolean results, which is not the intended logic. Option B is wrong because `=` is the assignment operator, not the equality comparison operator; using `num % 2 = 0` would cause a SyntaxError. Option C is wrong because `&&` is not a valid operator in Python; it is used in languages like C, Java, and JavaScript, but Python requires the keyword `and`.

49
MCQhard

A dictionary: d = {1: 'a', 2: 'b', 3: 'c'}. Which code will cause a KeyError?

A.d.get(4)
B.if 4 in d: d[4]
C.d[4]
D.d.setdefault(4, 'd')
AnswerC

Accessing d[4] raises KeyError because the dictionary only maps keys 1, 2 and 3; no entry exists for key 4. Unlike get(), which returns None for absent keys, subscript access demands the key be present, so the missing key triggers the exception directly.

Why this answer

Accessing a dictionary key that does not exist using square bracket notation (d[4]) raises a KeyError. Since the dictionary d has keys 1, 2, and 3, the key 4 is absent, so d[4] triggers the error.

Exam trap

The PCEP exam often tests the distinction between safe dictionary access methods (get, setdefault, in) and the direct indexing operator ([]), expecting candidates to know that only [] raises a KeyError for missing keys.

How to eliminate wrong answers

Option A is wrong because d.get(4) returns None (or a default value if provided) instead of raising an error, as the get() method is designed to safely handle missing keys. Option B is wrong because the 'if 4 in d:' condition checks for the key's existence before accessing d[4], so the block is never executed when the key is absent, preventing a KeyError. Option D is wrong because d.setdefault(4, 'd') inserts the key 4 with value 'd' into the dictionary and returns 'd', avoiding any error.

50
MCQmedium

A developer writes a function that modifies a global variable inside the function: count = 0 def increment(): count += 1 When called, an error occurs. What is the correct way to fix this?

A.Define count inside the function
B.Use the 'static' keyword
C.Pass count as an argument to the function
D.Use 'global count' inside the function
AnswerD

Assigning to count inside the function makes it a local variable, so the augmented assignment reads an unbound local and raises UnboundLocalError. Declaring 'global count' tells Python to bind the name to the module-level variable, allowing the increment to modify it.

Why this answer

The error occurs because Python treats 'count' as a local variable inside the function due to the assignment, but it is referenced before assignment. Using 'global count' inside the function explicitly tells Python to use the global variable, allowing modification. This is the correct fix for modifying a global variable from within a function.

Exam trap

PCEP often tests the misconception that Python has a 'static' keyword or that passing arguments can directly modify globals, when the correct answer is the 'global' declaration.

How to eliminate wrong answers

Option A is wrong because defining count inside the function would create a new local variable, not modify the global one, and would not resolve the intended behavior. Option B is wrong because Python does not have a 'static' keyword; that is from languages like C or Java. Option C is wrong because passing count as an argument would pass its value, but modifying it inside the function would still require returning and reassigning, which is not the direct fix for modifying the global variable.

51
MCQeasy

An application requires different messages based on temperature. Given: temp = 25 if temp > 30: print('Hot') elif temp > 20: print('Warm') else: print('Cool') What is the output?

A.No output
B.Hot
C.Cool
D.Warm
AnswerD

The first condition, temp > 30, evaluates false because 25 is not greater than 30. The elif condition, temp > 20, evaluates true, so its block runs and prints Warm; the else branch is skipped.

Why this answer

The condition `temp > 30` is False (25 is not greater than 30), so the first `if` block is skipped. The `elif temp > 20` condition is True (25 > 20), so the `print('Warm')` statement executes, outputting 'Warm'. Option D is correct.

Exam trap

The PCEP exam often tests the misconception that `elif` is optional or that the `else` block will execute even when a preceding `elif` is True, leading candidates to incorrectly choose 'Cool'.

How to eliminate wrong answers

Option A is wrong because the code will always produce output since the `else` clause ensures at least one branch executes, and here the `elif` condition is True. Option B is wrong because `temp` is 25, which is not greater than 30, so the `if` block for 'Hot' does not run. Option C is wrong because the `elif` condition `temp > 20` is True, so the `else` block (which prints 'Cool') is never reached.

52
Multi-Selecthard

Which THREE of the following are valid ways to create a list with elements 1, 2, 3? (Choose Three)

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

A list literal enclosed in square brackets with comma-separated values creates the list directly, producing exactly [1, 2, 3]. This is the most explicit list construction syntax and requires no iteration or conversion, satisfying the requirement for a list containing those three elements.

Why this answer

Option A, [1,2,3], is correct because a list literal enclosed in square brackets directly creates a list with the elements 1, 2, and 3 in order. Option B, list(range(1,4)), is correct because range(1,4) generates the integers 1, 2, 3 (the stop value 4 is exclusive), and wrapping it in the list() constructor materializes them as a list. Option D, [x for x in range(1,4)], is correct because this list comprehension iterates over range(1,4), producing the values 1, 2, 3 and collecting them into a new list.

Option C, (1,2,3), is not correct because parentheses create a tuple, not a list, and tuples are immutable and of a different type. Option E, {1,2,3}, is not correct because curly braces create a set, which is unordered and contains no duplicates, so it is not a list.

Exam trap

The PCEP exam often tests the distinction between list, tuple, and set literals, so candidates mistakenly choose curly-brace or parenthesis syntax as valid list creation methods.

53
MCQhard

A programmer needs to read a file line by line and process each line. Which of the following is the most memory-efficient and Pythonic approach?

A.with open('file.txt') as f: for line in f: print(line)
B.lines = open('file.txt').read().split('\n')
C.content = open('file.txt').read().splitlines()
D.for line in open('file.txt'): print(line)
AnswerA

Iterating directly over the file object yields one line at a time, so only a single line is held in memory. The with statement also guarantees the file is closed, satisfying the memory-efficiency and Pythonic requirements simultaneously.

Why this answer

It uses a `with` statement to ensure the file is properly closed after the block, and iterating directly over the file object reads one line at a time without loading the entire file into memory. This is both memory-efficient and Pythonic, as it leverages the file object's built-in iterator.

Exam trap

The PCEP exam often tests the distinction between using a `with` statement for guaranteed file closure versus relying on implicit garbage collection, and the misconception that reading the entire file at once is acceptable for small files, ignoring the principle of memory efficiency.

How to eliminate wrong answers

Option B is wrong because it reads the entire file into memory with `.read()`, then splits into a list, which is memory-inefficient for large files and does not close the file explicitly (relying on garbage collection). Option C is wrong because it also reads the entire file into memory with `.read()` and then splits into lines, wasting memory and leaving the file handle open. Option D is wrong because it does not use a `with` statement, so the file is not guaranteed to be closed promptly; it relies on the file object being garbage-collected, which is not Pythonic and can lead to resource leaks.

54
MCQhard

A function is supposed to modify a list passed as argument by appending an element. However, after calling the function, the original list remains unchanged. Which is the most likely cause?

A.The list is immutable.
B.The list is a tuple.
C.The function uses a local variable that shadows the global list.
D.The function reassigns the list parameter instead of mutating it.
AnswerD

Reassigning the parameter rebinds the local name to a new list object, so the caller's reference still points to the original, unmodified list. Appending mutates in place and would persist; assignment breaks that link, satisfying the stem's requirement that the original list stays unchanged.

Why this answer

In Python, when a list is passed to a function, the parameter refers to the same list object. If the function reassigns the parameter (e.g., `lst = [1, 2, 3]`), it only changes the local reference, not the original list. To modify the original list, the function must mutate it in-place using methods like `append()` or `extend()`, not reassign the parameter.

Exam trap

The PCEP exam often tests the distinction between mutating an object in-place versus reassigning the parameter name, exploiting the common misconception that reassigning a parameter inside a function will affect the original argument.

How to eliminate wrong answers

Option A is wrong because lists in Python are mutable objects; they can be modified in-place. Option B is wrong because a tuple is an immutable sequence, but the question explicitly states a list is passed, so this is a category error. Option C is wrong because while shadowing a global variable can cause confusion, the core issue here is that the function reassigns the parameter (a local variable) rather than mutating the list object itself; shadowing alone does not prevent mutation of the passed list.

55
MCQeasy

A student runs the following code in a Python 3.11 interactive session: >>> 7 // 2 What is displayed?

A.3.5
B.1
C.3
D.4
AnswerC

The double forward slash operator performs floor division, dividing the left operand by the right operand and rounding the result down to the nearest whole number. Since both 7 and 2 are integers, Python returns an integer, and 7 divided by 2 is 3 with a remainder, so the floor is 3.

Why this answer

Floor division with the double forward slash operator divides two numbers and rounds the result down to the nearest whole number. With integer operands, Python returns an integer. Because seven divided by two is three with a remainder of one, the floor value is three, and that integer is what the interactive session displays.

Exam trap

The trap here is confusing floor division with true division or with the modulo operator, since all three use similar symbols but produce different values.

56
MCQmedium

A team is developing a script that processes user input. They want to ensure that if the user enters a non-numeric value when asked for age, the program does not crash. Which approach should they use?

A.Use raw_input() and then int()
B.Use input() with a type check after input
C.Use int(input()) within a try-except block
D.Use a while loop to check if input.isdigit()
AnswerC

int() raises a ValueError when the input cannot be parsed as an integer, so wrapping the conversion in try-except lets the script catch that exception and handle it gracefully instead of terminating. This directly satisfies the requirement that non-numeric input must not crash the program.

Why this answer

Wrapping `int(input())` in a `try-except` block catches the `ValueError` that occurs when `int()` receives a non-numeric string. This prevents the program from crashing and allows graceful handling of invalid input, which is the standard Pythonic approach for robust user input validation.

Exam trap

The PCEP exam often tests the misconception that type checking after `input()` can prevent crashes, but candidates forget that `input()` always returns a string, making type checks like `isinstance()` useless without conversion, and that `isdigit()` is insufficient for numeric validation beyond simple positive integers.

How to eliminate wrong answers

Option A is wrong because `raw_input()` does not exist in Python 3 (it was renamed to `input()` in Python 2), and even if corrected, calling `int()` directly on non-numeric input will raise a `ValueError` and crash the program. Option B is wrong because using `input()` with a type check after input (e.g., `isinstance(value, int)`) is ineffective since `input()` always returns a string; the type check will never detect a non-numeric string as an integer, and the conversion to `int` would still crash if attempted. Option D is wrong because `input().isdigit()` only checks if the string consists entirely of digits, which fails for negative numbers, floats, or empty strings, and it does not handle the conversion or exception; the program would still crash if `int()` is called on a non-digit string.

57
MCQhard

A script uses 'import math' then calls 'math.sqrt(-1)'. What is the outcome?

A.ValueError
B.NaN
C.A complex number
D.AttributeError
AnswerA

math.sqrt() raises ValueError for negative arguments because it cannot return a real square root; it does not return a complex number or NaN. The constraint in the stem is the negative input -1, which triggers this specific exception rather than TypeError or ZeroDivisionError.

Why this answer

`math.sqrt()` in Python's math module does not support negative arguments; it raises a `ValueError` when given a negative number, as the function is designed for real numbers only. The error message is 'math domain error', indicating the input is outside the domain of the mathematical function.

Exam trap

The trap here is that candidates mistakenly think `math.sqrt()` can handle negative numbers by returning a complex number or NaN, confusing it with `cmath.sqrt()` or the behavior of some other languages' math libraries.

How to eliminate wrong answers

Option B is wrong because `math.sqrt(-1)` does not return NaN (Not a Number); Python's math module raises an exception rather than returning a special floating-point value like NaN. Option C is wrong because `math.sqrt()` does not return a complex number; to get a complex result, you must use `cmath.sqrt()` from the `cmath` module, which is designed for complex arithmetic. Option D is wrong because `AttributeError` would occur if the function `sqrt` did not exist on the `math` module, but `math.sqrt` is a valid attribute; the error is a `ValueError` due to the invalid argument, not a missing attribute.

58
Multi-Selectmedium

Which TWO of the following statements about Python's for loop are correct? (Choose Two)

Select 2 answers
A.It can be used with a while loop condition
B.It can iterate over any sequence
C.It always executes at least once
D.It can be used with an else clause
E.It is the only loop in Python
AnswersB, D

A Python for loop works with any iterable object, not just lists or strings, because it relies on the iterator protocol. It calls iter() to obtain an iterator and repeatedly invokes next() until StopIteration. This satisfies the stem's requirement that iteration works across sequences generally.

Why this answer

Option B is correct because Python's for loop is designed to iterate over any iterable object, including sequences such as lists, tuples, strings, and ranges, as well as non-sequence iterables like dictionaries, sets, and generators. Option D is correct because Python's for loop supports an optional else clause that executes after the loop completes normally, i.e., without encountering a break statement. Option A is incorrect because a for loop does not take a while-style boolean condition; it iterates over an iterable, whereas while loops use a condition.

Option C is incorrect because a for loop over an empty iterable executes zero times, unlike a do-while construct. Option E is incorrect because Python also provides the while loop, so the for loop is not the only loop.

Exam trap

The PCEP exam often tests the misconception that a `for` loop always executes at least once, but in reality it can iterate zero times over an empty sequence, and they also test the less-known fact that `for` loops support an `else` clause.

59
MCQeasy

Which of the following code snippets will correctly assign the integer 10 to the variable 'x'?

A.x == 10
B.x := 10
C.10 = x
D.x = 10
AnswerD

The assignment statement binds the name x to the integer object 10 using the single equals operator. No quotes, function call or comparison operator intervenes, so x references an int rather than a string or boolean, exactly as the question requires.

Why this answer

In Python, the assignment operator is a single equals sign (=), which binds the value on the right to the variable name on the left. The statement `x = 10` assigns the integer 10 to the variable 'x'.

Exam trap

The PCEP exam often tests the confusion between the assignment operator (`=`) and the equality operator (`==`), as well as the misuse of the walrus operator (`:=`) as a standalone assignment, to catch candidates who are not precise about Python syntax.

How to eliminate wrong answers

Option A is wrong because `==` is the equality comparison operator, not an assignment operator; it would evaluate to a Boolean (True or False) and not assign a value. Option B is wrong because `:=` is the walrus operator (assignment expression) introduced in Python 3.8, which is used within expressions and requires parentheses in most contexts; it is not a standalone assignment statement. Option C is wrong because Python does not allow assignment to a literal; the left side of an assignment must be a variable name, not a value like 10.

60
MCQmedium

A program uses a variable named 'list' that shadows the built-in list type. Later, the code tries to create a new list using list([1,2,3]) but gets a TypeError. What is the most likely cause?

A.The argument [1,2,3] is invalid because it contains integers.
B.The variable 'list' is now an integer or other non-callable type.
C.The list constructor expects a tuple, not a list.
D.The code is missing an import for the list type.
AnswerB

Rebinding the name 'list' to a non-callable value, such as an integer, means list([1,2,3]) attempts to call that object, raising TypeError. The built-in list type is shadowed in that scope, so the original constructor is no longer reachable via that name.

Why this answer

When a variable named 'list' is assigned a value (e.g., an integer), it shadows the built-in `list` type in the current scope. Later, calling `list([1,2,3])` attempts to call the variable `list` as a function, but since it now holds a non-callable object (like an integer), Python raises a TypeError. This is a classic name-shadowing issue in Python.

Exam trap

Python Institute often tests the concept of name shadowing, where candidates mistakenly think the error is due to invalid arguments or missing imports, rather than recognizing that reassigning a built-in name makes it non-callable.

How to eliminate wrong answers

Option A is wrong because `[1,2,3]` is a perfectly valid list literal containing integers, and the list constructor accepts any iterable, including lists. Option C is wrong because the list constructor accepts any iterable (list, tuple, string, etc.), not just tuples; a list argument is valid. Option D is wrong because `list` is a built-in type in Python and does not require any import; it is always available in the global namespace.

61
Multi-Selecteasy

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

Select 2 answers
A.'a' > 'b'
B.5 > 10
C.3 == 3
D.bool(0)
E.not False
AnswersC, E

The equality operator compares the integer objects 3 and 3, which hold identical values, so the expression returns the Boolean True. This satisfies the stem's requirement for expressions evaluating to True, since Python's == checks value equivalence rather than object identity.

Why this answer

Option C (3 == 3) is correct because the equality operator compares the two integer literals 3 and 3, which are identical values, so the expression evaluates to True. Option E (not False) is correct because the logical not operator inverts the Boolean value False, yielding True. Option A ('a' > 'b') is incorrect because string comparison uses lexicographic ordering by character code point, and 'a' (97) is less than 'b' (98), so the expression is False.

Option B (5 > 10) is incorrect because 5 is not greater than 10, so it evaluates to False. Option D (bool(0)) is incorrect because 0 is a falsy value in Python, so bool(0) returns False.

Exam trap

Python Institute often tests the distinction between truthy/falsy values and the behavior of bool() with numeric zero, leading candidates to mistakenly think bool(0) returns True.

62
MCQhard

A programmer writes the following code to convert a user's input to a number and add 5: age = input('Enter age: ') new_age = int(age) + 5 print(new_age) If the user enters 'twenty', what happens?

A.The program prints 25 because int('twenty') returns 20.
B.The program prints 'twenty5' because int() converts the string to 20 and concatenates 5.
C.A ValueError is raised because int() cannot convert the string 'twenty' to an integer.
D.A SyntaxError occurs because 'twenty' is not a number.
AnswerC

The int() function attempts to parse the string argument as an integer. The string 'twenty' does not represent a valid integer literal, so Python raises a ValueError. This is a runtime error, not a syntax error, because the code is syntactically correct. The program will terminate with a traceback unless the exception is handled.

Why this answer

The int() function raises a ValueError when given a string that is not a valid integer literal. Since 'twenty' is not numeric, the conversion fails at runtime. The code itself is syntactically valid, so it is not a SyntaxError.

The program will crash with a traceback unless the error is caught.

Exam trap

The trap here is confusing runtime ValueError with compile-time SyntaxError, or assuming int() understands English number words.

63
Multi-Selectmedium

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

Select 2 answers
A.str
B.set
C.dict
D.list
E.tuple
AnswersA, E

Strings cannot be altered after creation; any operation such as concatenation or slicing returns a new str object rather than modifying the original in place. This immutability makes str hashable and usable as dictionary keys, satisfying the question's requirement for an immutable Python data type.

Why this answer

Option A (str) is correct because Python strings are immutable: once created, their characters cannot be changed in place, and any operation like concatenation or slicing returns a new string object. Option E (tuple) is correct because tuples are immutable sequences; after creation you cannot add, remove, or reassign their elements, and attempting to do so raises a TypeError. The unmarked options do not belong because set (B), dict (C), and list (D) are all mutable container types, meaning their contents can be modified in place via methods such as add(), update(), or append().

Exam trap

The PCEP exam often tests the distinction between mutable and immutable types by pairing tuple (immutable) with list (mutable), hoping candidates confuse tuple's immutability with list's mutability, or mistakenly think that because a tuple can contain mutable objects, the tuple itself is mutable.

64
MCQmedium

A programmer is debugging a Python script that is supposed to concatenate a user's first and last names with a space between them. The code is: first = 'John' last = 'Doe' full = first + ' ' + last print(full) What is the output of this script?

A.John' 'Doe
B.JohnDoe
C.An error occurs because you cannot concatenate strings with the + operator.
D.John Doe
AnswerD

The code concatenates the string 'John', a space, and 'Doe' using the + operator. The space is a string literal ' ' and is included between the two names. The resulting string is 'John Doe', which is then printed. This is the correct output.

Why this answer

The + operator concatenates strings. The expression first + ' ' + last evaluates to 'John' + ' ' + 'Doe', which is 'John Doe'. The print function then displays that string.

The other options misinterpret the space, the quotes, or the validity of string concatenation.

Exam trap

The trap here is overlooking the explicit space string or thinking that concatenation requires a special method rather than the + operator.

65
Multi-Selectmedium

Which FOUR of the following are valid ways to create a list with elements 1, 2, 3? (Choose four.)

Select 4 answers
A.[1, 2, 3,]
B.list(range(1, 4))
C.[1, 2, 3]
D.list(1, 2, 3)
E.list((1, 2, 3))
AnswersA, B, C, E

A trailing comma after the final element is permitted in Python list displays, so [1, 2, 3,] builds the list [1, 2, 3] correctly. The parser treats the comma as a separator before the closing bracket, making this a valid literal.

Why this answer

Option A, [1, 2, 3,], is correct because Python allows a trailing comma after the last element in a list literal, so it still produces the list [1, 2, 3]. Option B, list(range(1, 4)), is correct because range(1, 4) yields 1, 2, and 3 (the stop value 4 is exclusive), and list() converts that iterable into [1, 2, 3]. Option C, [1, 2, 3], is correct as the standard list literal syntax that directly creates the list [1, 2, 3].

Option E, list((1, 2, 3)), is correct because (1, 2, 3) is a tuple containing those three integers, and list() converts the tuple into the list [1, 2, 3]. Option D, list(1, 2, 3), is not valid because list() takes at most one argument (an iterable), so passing three separate integer arguments raises a TypeError.

Exam trap

Python Institute often tests the distinction between the `list()` constructor requiring a single iterable argument versus the mistaken belief that it accepts multiple positional arguments, as in option D.

66
MCQhard

A developer runs the code from the exhibit and gets the error shown. Which of the following is the most likely cause?

A.There is a typo in the variable name.
B.The variable 'result' was never assigned a value.
C.The print function requires an import.
D.The variable 'result' is a string, not an integer.
AnswerB

Referencing a name that was never bound raises `NameError`, which is exactly what the exhibit shows. Python resolves names at runtime, so `result` must be assigned before use; an unassigned variable has no object to return. This satisfies the stem's constraint that the traceback names `result` as undefined.

Why this answer

The error message indicates that the variable 'result' is referenced before it has been assigned any value. In Python, using a variable that has never been assigned raises a NameError. The code attempts to print 'result', but no assignment to 'result' exists in the provided code, so Python cannot resolve the name.

Exam trap

The PCEP exam often tests the distinction between a variable that exists but has the wrong type (TypeError) and a variable that has never been assigned (NameError), leading candidates to incorrectly focus on type mismatches instead of the missing assignment.

How to eliminate wrong answers

Option A is wrong because a typo in the variable name would still cause a NameError, but the error message would reference the misspelled name, not 'result'. Option C is wrong because the print function is a built-in in Python 3 and does not require any import; it is always available. Option D is wrong because the error is a NameError, not a TypeError; the variable 'result' does not exist at all, so its type is irrelevant.

67
Multi-Selectmedium

A programmer is writing a Python script and needs to create variables that hold a user's name, age, and whether they are a student. Which TWO of the following assignments are syntactically valid and will execute without error in Python? (Choose two.)

Select 2 answers
A.class = "Math"
B.user_name = "Alice"
C.user-name = "Bob"
D.is_student = True
E.2nd_age = 25
AnswersB, D

This assignment uses a valid identifier: it starts with a letter, contains only letters and underscores, and is not a keyword. The string literal is properly quoted with double quotes. Python allows this and binds the string 'Alice' to the variable user_name without any syntax error.

Why this answer

Valid Python identifiers must start with a letter or underscore, contain only letters, digits, and underscores, and must not be keywords. The assignments user_name = "Alice" and is_student = True satisfy these rules. Names starting with a digit, using hyphens, or using reserved words like class are invalid and cause syntax errors.

Exam trap

The trap here is focusing only on the value side of the assignment and overlooking identifier rules such as no leading digits, no hyphens, and no keywords.

68
MCQmedium

A developer writes: print('Hello' + 5). What is the result?

A.Hello 5
B.TypeError
C.SyntaxError
D.Hello5
AnswerB

Python's + operator on str requires both operands to be str; concatenating a str with an int raises TypeError rather than coercing the integer, because Python is strongly typed and defines no implicit int-to-str conversion for this operation.

Why this answer

In Python, the + operator performs string concatenation only when both operands are strings. Attempting to concatenate a string ('Hello') with an integer (5) raises a TypeError because Python does not implicitly convert the integer to a string for concatenation. This is a fundamental type safety feature of the language.

Exam trap

This exact scenario tests whether candidates understand that Python does not implicitly convert an integer to a string for concatenation, unlike loosely-typed languages.

How to eliminate wrong answers

Option A is wrong because it suggests that Python would automatically insert a space between the string and integer, which is not the case; the + operator does not add spaces. Option C is wrong because the code is syntactically valid (no missing colons, parentheses, or keywords) — the error occurs at runtime, not during parsing. Option D is wrong because it implies Python would implicitly convert the integer 5 to the string '5' and concatenate, but Python's strict type system prevents this without an explicit str() call.

69
MCQhard

A programmer wants to create a function that can accept any number of keyword arguments and store them in a dictionary. Which function definition is correct?

A.def func(kwargs):
B.def func(**kwargs):
C.def func(**args):
D.def func(*kwargs):
AnswerB

The double-asterisk prefix **kwargs in a parameter list collects arbitrary keyword arguments into a dictionary named kwargs, satisfying the stem's requirement to accept any number of keyword arguments. Single-asterisk *args would instead gather positional arguments into a tuple, which does not meet the stated constraint.

Why this answer

The **kwargs parameter in a function definition collects any number of extra keyword arguments into a dictionary. The double asterisk (**) is the Python syntax for capturing keyword arguments, and 'kwargs' is the conventional name for the resulting dictionary.

Exam trap

The PCEP exam often tests the distinction between *args (positional arguments packed into a tuple) and **kwargs (keyword arguments packed into a dictionary), and the trap here is that candidates confuse the single asterisk for keyword arguments or forget that the double asterisk is required for dictionary packing.

How to eliminate wrong answers

Option A is wrong because 'kwargs' without the double asterisk is just a regular parameter name; it does not collect keyword arguments and will cause a TypeError if keyword arguments are passed. Option C is wrong because '**args' uses the conventional name for positional arguments ('args') with the keyword argument syntax, which is misleading and non-standard, though technically it would work; however, the exam expects the conventional **kwargs. Option D is wrong because '*kwargs' uses a single asterisk, which collects extra positional arguments into a tuple, not keyword arguments into a dictionary.

70
MCQhard

A programmer writes: x = 10 y = 4 print(x // y, x % y, x / y) What is printed?

A.2 0.5 2.5
B.2 2 2.0
C.2 2 2.5
D.2.5 2 2
AnswerC

The // operator performs floor division: 10 // 4 equals 2 because 4 goes into 10 twice. The % operator gives the remainder: 10 % 4 equals 2. The / operator performs true division and returns a float: 10 / 4 equals 2.5. Printed together, they produce '2 2 2.5'.

Why this answer

The floor division operator // returns the largest integer less than or equal to the quotient, so 10 // 4 is 2. The modulus operator % returns the remainder, so 10 % 4 is 2. True division / returns a float, so 10 / 4 is 2.5.

Printing these in order gives '2 2 2.5'.

Exam trap

The trap here is confusing the results of //, %, and /, especially assuming that % returns a fractional part or that // returns a float.

71
MCQhard

A Python script processes a large file and runs out of memory. Which solution is most appropriate?

A.Increase the memory allocation
B.Use a while loop to read chunks
C.Read the entire file into memory and split
D.Process the file line by line using a for loop
AnswerD

Iterating with a for loop reads one line at a time, so only a single line resides in memory rather than the whole file. This directly resolves the out-of-memory constraint by keeping peak memory proportional to line length.

Why this answer

Reading a file line by line with a for loop in Python processes one line at a time, keeping only the current line in memory. This avoids loading the entire file into RAM, which is the root cause of the memory exhaustion when dealing with large files.

Exam trap

The PCEP exam often tests the misconception that reading a file in chunks with a while loop is the best approach, when in fact the idiomatic for loop over the file object is simpler, safer, and the recommended pattern in Python for line-by-line processing.

How to eliminate wrong answers

Option A is wrong because simply increasing memory allocation does not solve the underlying inefficiency; it only postpones the problem and may not be feasible or cost-effective. Option B is wrong because using a while loop to read chunks (e.g., file.read(chunk_size)) still requires manual buffer management and can still lead to memory issues if chunks are too large or not handled properly; the idiomatic Python approach is to iterate over the file object directly. Option C is wrong because reading the entire file into memory and then splitting it is exactly the behavior that causes memory exhaustion; it defeats the purpose of processing a large file.

72
MCQhard

A developer writes a loop to find the first even number in a list: numbers = [3, 5, 8, 10] for n in numbers: if n % 2 == 0: print(n) break else: print('No even number') What is printed?

A.8
B.No even number
C.8 10
D.8 No even number
AnswerA

The loop checks each number with the modulo operator. The first two values, 3 and 5, are odd, so the condition fails. When n becomes 8, n % 2 equals 0, so the value is printed and break exits the loop immediately. Because the loop was broken, the else clause is skipped, leaving 8 as the only output.

Why this answer

A for loop's else clause executes only if the loop finishes without encountering break. Here the loop breaks when the first even value 8 is found, so the else is bypassed and only 8 is printed. The modulo test n % 2 == 0 correctly identifies even numbers.

Exam trap

The trap here is reading the loop's else as an ordinary conditional else, when it actually runs only when no break occurred.

73
MCQmedium

A developer defines a function and calls it as shown: def greet(name, greeting='Hello'): return greeting + ', ' + name print(greet('Ana')) What is printed?

A.A TypeError is raised.
B.Hello, Ana
C.Hello, greeting
D.Ana, Hello
AnswerB

The parameter greeting has a default value of 'Hello'. When greet is called with only the positional argument 'Ana', name receives that value and greeting falls back to its default. The function concatenates the two strings with a comma and space, producing 'Hello, Ana', which print then displays.

Why this answer

Default parameter values let a caller omit arguments that have sensible fallbacks. Because greet is invoked with only 'Ana', that value binds to name while greeting uses its default 'Hello'. The concatenation then yields the string 'Hello, Ana', which is printed to the console.

Exam trap

The trap here is forgetting that an omitted argument silently uses the parameter's default rather than causing an error or leaving the placeholder empty.

74
MCQmedium

A developer wants to store a collection of unique employee IDs that will be checked frequently for membership. Duplicate IDs must be automatically ignored, and the order of IDs does not matter. Which built-in data type best fits this requirement?

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

A set stores only unique elements and automatically discards duplicates when items are added. Its hash-based implementation provides average constant-time membership testing with the in operator, which suits frequent ID lookups. Because the order of employee IDs is explicitly unimportant, the set's unordered nature is not a drawback for this requirement.

Why this answer

The set type is designed for unordered collections of unique hashable elements. Adding an existing employee ID leaves the set unchanged, and the in operator performs an average constant-time membership test thanks to hashing. Since the order of IDs is irrelevant and duplicates must be eliminated automatically, a set matches the described requirements more directly than any ordered sequence or key-value mapping.

Exam trap

The trap here is reaching for a dictionary because both it and a set guarantee uniqueness, forgetting that a dictionary demands a value for each key and models pairs rather than a plain collection.

Page 1 of 2 · 122 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Computer Programming and Python Fundamentals questions.