Courseiva

CCNA Computer Programming and Python Fundamentals Questions

73 of 137 questions · Page 1/2 · Computer Programming and Python Fundamentals · Answers revealed

1
Multi-Selecteasy

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

Select 2 answers
A.my-var
B._myVar
C.2ndValue
D.class
E.my_var
AnswersB, E

Underscore at start is allowed.

Why this answer

In Python, variable names can start with an underscore, and `_myVar` follows the naming rules: it begins with a letter or underscore, contains only letters, digits, or underscores, and is not a reserved keyword. Underscore-prefixed names are commonly used for internal or private variables by convention.

Exam trap

The PCEP exam often tests the rule that hyphens are invalid in variable names (tricking candidates who confuse them with underscores) and that keywords like `class` are reserved, even though they look like valid identifiers.

2
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

Catches all invalid literals, logs line number, and continues.

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.

3
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

Correct: num = num * 2 just rebinds num, not the list.

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.

4
Drag & Dropmedium

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

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

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

Why this order

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.

5
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

Correct as described.

Why this answer

The string 'Hello World' is first operated on by replace('o', '0') which replaces all occurrences of 'o' with '0', resulting in 'Hell0 W0rld'. Then .upper() converts all characters to uppercase, yielding 'HELL0 W0RLD'. Therefore, option C is correct.

Option A is 'hell0 w0rld' which would require .lower() after replace. Option B is 'HELLO WORLD' which does not apply the replacement. Option D is 'Hell0 W0rld' which is only the result after replace but without .upper().

Exam trap

This question tests chaining string methods. A common mistake is to confuse the order of operations or to forget that replace is case-sensitive (only replaces lowercase 'o').

6
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

Selective exception handling allows graceful continuation.

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.

7
MCQmedium

Refer to the exhibit. What is the output when the following code is executed: print(calculate_discount(100, 0.6))

A.Discount too high
B.40.0
C.100
D.Discount too high followed by 100
AnswerD

The print statement outputs the message, then the function returns 100 which is printed.

Why this answer

The code defines a function `calculate_discount(price, discount)` that first checks if the discount is 0.6 or higher. Since 0.6 is exactly equal to 0.6, the condition `if discount >= 0.6` is true, so it prints 'Discount too high' and then returns the original price (100). The `print()` statement outside the function outputs the return value, which is 100, resulting in the output 'Discount too high' followed by '100' on the next line.

Exam trap

The PCEP exam often tests the distinction between a function's printed output and its return value, leading candidates to overlook that both the print inside the function and the print of the return value appear in the output.

How to eliminate wrong answers

Option A is wrong because it only shows 'Discount too high' and omits the returned value 100, which is also printed. Option B is wrong because 40.0 would be the result if the discount were applied (100 * 0.4), but the condition triggers the early return without applying the discount. Option C is wrong because it shows only 100, ignoring the printed message 'Discount too high' that occurs before the return.

8
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

This is the typical cause of a NameError in Python.

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.

9
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

Correct. Python lists are heterogeneous containers; they can store elements of different data types.

Why this answer

Only two options are correct: A and E. Option A is correct because Python lists can contain elements of different data types. Option E is correct because len() returns the number of elements in a list.

Options B, C, D are incorrect: B is wrong because lists are mutable and unhashable, hence cannot be dictionary keys; C is wrong because index starts at 0; D is wrong because lists are mutable.

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.

10
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

i=1 is skipped.

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.

11
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

nonlocal allows modification.

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.

12
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

List comprehension creates a new list with increments, original unchanged.

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

13
MCQhard

A company is developing a data processing pipeline that must handle large datasets efficiently. They notice that using a list comprehension to filter data is slower than expected. Which alternative approach would likely improve performance?

A.Using the map() function
B.Using a for loop with append
C.Using a generator expression
D.Using a lambda function
AnswerC

Generators yield items one by one and avoid storing the entire list, reducing memory and often improving speed.

Why this answer

Generator expressions produce items lazily, one at a time, without storing the entire filtered result in memory. This reduces memory overhead and can improve performance when processing large datasets, as the pipeline can iterate over generated items without building a full list first.

Exam trap

The PCEP exam often tests the misconception that map() or lambda functions are inherently faster for filtering, when in fact the key performance difference lies in lazy evaluation versus eager list construction, which is the core advantage of generator expressions.

How to eliminate wrong answers

Option A is wrong because map() applies a function to every item in an iterable and returns a map object, but it does not inherently filter data; filtering requires additional logic (e.g., combining with filter()), and map() still produces an iterator, not a performance gain over list comprehensions for filtering. Option B is wrong because using a for loop with append is typically slower than a list comprehension due to the overhead of repeated method calls and dynamic list resizing, making it a less efficient alternative. Option D is wrong because a lambda function is just an anonymous function definition; it does not by itself improve performance—it must be used with other constructs like map() or filter(), and the performance characteristics depend on the surrounding code, not the lambda itself.

14
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

TypeError occurs when an operation is applied to an object of inappropriate type. However, multiplying integer by string is permitted for repetition, so no TypeError.

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.

15
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

Correct iteration and method call.

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

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

Floor division returns the integer part, 3.

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
MCQhard

You are a developer in a data science team using Python for analysis. A colleague wrote a script that downloads a CSV file from a URL, parses it using csv.DictReader, and prints summary statistics. The script works on his machine but fails on yours with 'UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 100: invalid continuation byte'. The CSV file contains text in multiple languages, including French accents. The error occurs in the csv.DictReader call. You need to fix the script to work on any machine. Which approach is best?

A.Read the file in binary mode and decode with 'utf-8' ignoring errors.
B.Open the file with encoding='utf-8-sig' to handle BOM.
C.Use the errors='replace' parameter in the open() call.
D.Open the file with encoding='latin-1' (or 'cp1252') to handle a wider range of bytes.
AnswerD

latin-1 can decode any byte, preserving data, though may not be accurate for all characters.

Why this answer

The error indicates the CSV file contains bytes that are not valid UTF-8, such as 0xe9 (é in Latin-1). Opening the file with encoding='latin-1' (or 'cp1252') maps every byte to the corresponding Unicode code point without decoding errors, which is a practical fix for CSV files with mixed-language text that are not strictly UTF-8. This approach ensures the file can be read on any machine regardless of the default system encoding.

Exam trap

The PCEP exam often tests the misconception that 'utf-8-sig' or error-handling parameters like 'ignore' or 'replace' are universal fixes, when in fact they either address a different problem (BOM) or corrupt data, whereas specifying the correct encoding (latin-1) is the proper solution for files with extended Latin characters.

How to eliminate wrong answers

Option A is wrong because reading in binary mode and decoding with 'utf-8' ignoring errors silently discards problematic bytes, corrupting the data and potentially breaking CSV parsing. Option B is wrong because 'utf-8-sig' only handles a UTF-8 BOM (Byte Order Mark) at the start of the file, but the error here is caused by non-UTF-8 bytes in the middle of the file, not a BOM issue. Option C is wrong because errors='replace' replaces undecodable bytes with the replacement character (U+FFFD), which alters the data and can introduce invalid characters that break CSV parsing or produce incorrect statistics.

18
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

List comprehension.

Why this answer

It uses a list comprehension with `range(1,4)`, which generates the numbers 1, 2, and 3 and collects them into a new list. This is a concise and valid Python syntax for creating a list from an iterable.

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.

19
MCQmedium

A developer is writing a script to process user input. The script should repeatedly ask for a number until a valid integer is entered. Which loop structure is most appropriate?

A.while loop with a condition
B.for loop
C.do-while loop
D.Recursion
AnswerA

A while loop can run until a condition is met, ideal for input validation.

Why this answer

A while loop with a condition is the most appropriate because it allows the script to repeatedly prompt for input until a valid integer is entered, checking the condition before each iteration. In Python, the while loop continues as long as the condition evaluates to True, making it ideal for indefinite iteration where the number of repetitions is unknown beforehand. This pattern is commonly used with a try-except block to validate integer conversion.

Exam trap

The PCEP exam often tests the misconception that a for loop can handle indefinite repetition by using a large range, but the trap is that for loops are designed for definite iteration over a sequence, not for conditions that depend on runtime input validation.

How to eliminate wrong answers

Option B (for loop) is wrong because a for loop iterates over a fixed sequence (e.g., a range or list), which is unsuitable for an unknown number of repetitions until valid input is received. Option C (do-while loop) is wrong because Python does not have a built-in do-while loop; the concept exists in other languages but cannot be directly used in Python without emulating it with a while loop. Option D (Recursion) is wrong because while recursion could theoretically work, it risks hitting Python's recursion limit (default 1000) and is less efficient and harder to read than a simple while loop for this repetitive input validation task.

20
MCQhard

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

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

Concise and idiomatic list comprehension.

Why this answer

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.

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

22
MCQmedium

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

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

Pythonic and direct.

Why this answer

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

23
Multi-Selecteasy

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

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

Valid identifier.

Why this answer

Python variable names can contain letters, digits, and underscores, and must start with a letter or underscore. 'value_2' starts with a letter and uses an underscore, making it valid.

Exam trap

The PCEP exam often tests the rule that hyphens are illegal in variable names, as candidates may confuse them with underscores or assume they are allowed like in some other languages.

24
MCQeasy

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

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

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

Why this answer

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.

25
MCQhard

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

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

List comprehension is preferred.

Why this answer

Uses a list comprehension, which is the most Pythonic and efficient way to create a list because it combines iteration and list construction in a single, readable expression. It avoids the overhead of repeated method calls (like `append`) and is faster than `map` with a lambda due to reduced function call overhead.

Exam trap

The PCEP exam often tests the distinction between list comprehensions and generator expressions, trapping candidates who confuse the lazy evaluation of generators with the eager construction of lists.

How to eliminate wrong answers

Option B is wrong because it uses an explicit loop with `append`, which is less efficient and less Pythonic than a list comprehension, though it produces the same result. Option C is wrong because `map` with a lambda is less efficient and less readable than a list comprehension; the lambda adds function call overhead for each element, and `map` returns an iterator in Python 3, requiring an explicit `list()` call to get a list. Option D is wrong because it creates a generator expression (not a list), which yields values lazily and cannot be indexed or sliced like a list; it does not produce a list of squares.

26
MCQeasy

Consider the following code: x = input('Enter a number: ') print(x + x) A user enters 5 at the prompt. What is printed?

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

String '5' repeated twice.

Why this answer

55 because Python's input() function returns a string. When the user enters 5, it is stored as the string '5'. If the code then uses the + operator to concatenate this string with itself (e.g., print(input() + input()) or print(x + x)), the result is '55', not numeric addition.

Exam trap

The PCEP exam often tests the distinction between string concatenation and numeric addition, exploiting the fact that `input()` returns a string, so candidates mistakenly assume automatic type conversion to integer.

How to eliminate wrong answers

Option B is wrong because it assumes the input is converted to an integer and added (5+5=10), but no `int()` conversion is performed. Option C is wrong because it suggests only one '5' is printed, ignoring the concatenation of the two strings. Option D is wrong because it implies multiplication (5*5=25), which would require the `*` operator and numeric conversion.

27
MCQmedium

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

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

Catches ImportError and exits gracefully.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

28
Multi-Selecthard

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

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

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

Why this answer

`y = x` creates a reference to the same list object, not a copy. When `y.append(4)` is called, it modifies the shared list, so `x` becomes `[1, 2, 3, 4]`. This demonstrates that assignment in Python does not copy objects; it binds a new name to the existing object.

Exam trap

The PCEP exam often tests the distinction between reference assignment and copying; the trap here is that candidates mistakenly think `y = x` creates a new list, leading them to believe `x` remains unchanged after `y.append(4)`.

29
Multi-Selecthard

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

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

Value comparison coerces types, both equal 3.

Why this answer

`int(3.0)` converts the float 3.0 to the integer 3, and the `==` operator compares values, not types. Since 3.0 and 3 represent the same numeric value, the comparison returns True. This demonstrates that `==` performs value equality, not identity.

Exam trap

The PCEP exam often tests the difference between `is` (identity) and `==` (equality), and the trap here is that candidates assume `is` compares values like `==` does, or they forget that integer interning is an implementation detail not guaranteed for all values.

30
MCQhard

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

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

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

Why this answer

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.

31
MCQhard

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

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

Lists are unhashable and cannot be used as dictionary keys.

Why this answer

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.

32
MCQhard

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

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

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

Why this answer

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.

33
MCQhard

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

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

Index 1 'Java', first 3 chars.

Why this answer

The JSON data is loaded into a Python dictionary. The key 'languages' maps to a list of strings. Indexing with [1] retrieves the second element, which is 'Java'.

Then slicing with [:3] extracts the first three characters, resulting in 'Jav'. Therefore, option B is correct.

Exam trap

The PCEP exam often tests the combination of list indexing and string slicing, where candidates may forget that slicing returns a substring of the specified length, not the full string, or may misidentify the zero-based index of the list element.

How to eliminate wrong answers

Option A is wrong because IndexError would only occur if the index or slice is out of range, but here the list has at least two elements and the string 'Java' has more than three characters, so no error is raised. Option C is wrong because it assumes the slice [:3] returns the full string 'Java', but slicing with [:3] returns only the first three characters, not the entire string. Option D is wrong because it confuses the index: [1] accesses the second element 'Java', not the first element 'Python', and slicing [:3] on 'Python' would give 'Pyt', but that is not what the code does.

34
MCQeasy

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

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

Correctly converts the input string to an integer.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

35
MCQeasy

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

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

Returning allows the result to be used in other calculations.

Why this answer

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.

36
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

not (a > b) = not (5 > 10) = not False = True

Why this answer

Only option C evaluates to True. Option C: not (5 > 10) = not False = True. Option D: a == b or False = 5 == 10 or False = False or False = False.

Options A and B are also False.

37
Multi-Selecteasy

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

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

Valid: letters and underscore.

Why this answer

`total_sum` starts with a letter and contains only letters and underscores, which are allowed in Python identifiers. Python variable names must begin with a letter or underscore and can be followed by letters, digits, or underscores.

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.

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

39
MCQhard

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

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

The error message is printed, then finally runs.

Why this answer

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

40
MCQeasy

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

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

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

Why this answer

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.

41
Multi-Selecteasy

Which TWO of the following are valid Python variable names?

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

Letters, underscores, and digits are allowed.

Why this answer

Python variable names must start with a letter or underscore, and can contain letters, digits, and underscores. 'my_var2' starts with a letter and contains only valid characters, so it is a valid identifier.

Exam trap

The PCEP exam often tests the rule that variable names cannot start with a digit, and the distinction between hyphens (which are operators) and underscores (which are valid identifier characters), leading candidates to mistakenly accept '2nd_var' or 'my-var' as valid.

42
Multi-Selecteasy

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

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

_myVar is valid: it starts with an underscore and contains only letters and underscores.

Why this answer

Options A (_myVar) and D (my_var) are the two correct variable names. Option B (my Var) is invalid because it contains a space, option C (my-var) contains a hyphen which is not allowed, and option E (2ndPlace) starts with a digit.

Exam trap

The PCEP exam often tests the rule that hyphens are invalid in variable names, as candidates may confuse them with underscores or assume they are allowed like in other languages (e.g., Lisp or some shell scripting).

43
MCQmedium

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

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

Uses default b=5.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

44
MCQeasy

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

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

Exception handling allows the script to continue processing other rows.

Why this answer

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.

45
MCQeasy

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

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

Returning a new list keeps the function pure and reusable.

Why this answer

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.

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

47
MCQmedium

What is the output of the code in the exhibit?

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

The condition is false, so the else block executes and prints 'Less or equal'.

Why this answer

The code assigns x=10 and y=20 (assuming the exhibit shows these values), then checks if x > y. Since 10 > 20 is False, the if block does not execute, and the else block prints 'Less or equal'. Therefore, option C is correct.

Exam trap

A common pitfall: candidates may incorrectly assume the if block executes or forget that else runs when the condition is false, leading them to choose 'Greater' instead of correctly identifying the else output.

How to eliminate wrong answers

Option A is wrong because it suggests both branches execute, but Python's if-else structure ensures only one block runs based on the condition. Option B is wrong because the syntax is valid: comparison operators (>) and print() are correctly used, so no SyntaxError occurs. Option C is wrong because it is the actual output, not 'Greater', but the question asks for the correct answer, which is D (the output is 'Less or equal', not 'Greater').

48
MCQeasy

Which of the following variable names is valid in Python?

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

Underscores are allowed and often used for private attributes.

Why this answer

(_private) is valid because Python allows variable names to start with an underscore. Identifiers can consist of letters, digits, and underscores, but must not begin with a digit. The underscore is treated as a letter, so _private conforms to Python's naming rules.

Exam trap

The PCEP exam often tests the rule that identifiers cannot start with a digit, leading candidates to mistakenly think that any non-alphabetic starting character is invalid, but underscores are explicitly allowed.

How to eliminate wrong answers

Option A is wrong because variable names cannot start with a digit; '1st_value' begins with '1', which violates Python's identifier syntax. Option C is wrong because 'class' is a reserved keyword in Python and cannot be used as a variable name. Option D is wrong because the hyphen '-' is not a valid character in Python identifiers; only underscores are allowed for separation, not dashes.

49
Multi-Selecteasy

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

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

Converts tuple to list.

Why this answer

The `list()` constructor can take an iterable, such as a tuple, and convert it into a new list. `list((1, 2, 3))` explicitly creates a list `[1, 2, 3]` from the tuple `(1, 2, 3)`. This is a standard and valid way to create a list in Python.

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.

50
MCQmedium

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

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

Precise exception handling allows logging and skipping only problematic items.

Why this answer

It combines targeted exception handling with loop continuity. By placing a try-except inside the loop, you catch KeyError (and optionally other expected exceptions) for each individual user ID, log or handle the failure, and then continue processing the next item. This avoids crashing the entire loop while still allowing normal processing for valid data, which is more robust than blindly using .get() on deeply nested structures or catching all exceptions outside the loop.

Exam trap

The Python Institute often tests the distinction between catching exceptions at the loop level versus inside the loop, and candidates mistakenly choose wrapping the entire loop in a try-except (Option C) because they think it handles all errors, not realizing it terminates the loop on the first failure.

How to eliminate wrong answers

Option A is wrong because .get() only handles missing keys at the level it is called; if a nested key is missing, accessing it on the result of .get() will still raise a KeyError unless every intermediate access also uses .get() with a default, which becomes cumbersome and error-prone for deeply nested JSON. Option B is wrong because checking key existence with 'in' for every key before access leads to verbose, repetitive code and still requires handling missing keys at multiple levels, often resulting in deeply nested if statements that are hard to maintain. Option C is wrong because wrapping the entire loop in a try-except catches any exception from any iteration, causing the loop to abort entirely on the first error, which defeats the requirement that the application must continue functioning even with incomplete data.

51
MCQhard

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

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

Uppercase with underscores for constants.

Why this answer

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.

52
MCQeasy

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

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

Correct calculation.

Why this answer

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.

53
MCQeasy

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

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

Most straightforward.

Why this answer

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.

54
MCQhard

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

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

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

Why this answer

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.

55
MCQmedium

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

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

Correct syntax.

Why this answer

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

56
Matchingmedium

Match each Python list method to its effect.

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

Concepts
Matches

Adds an item to the end of the list

Inserts an item at a given position

Removes the first occurrence of a value

Removes and returns an item at a given index

Sorts the list in ascending order in place

Why these pairings

The correct matches are: insert inserts at an index, remove deletes first occurrence of a value, pop removes and returns an element by index. Common confusions involve swapping append (adds a single element) and extend (adds elements from an iterable).

57
MCQmedium

A junior developer is tasked with writing a Python script that reads a list of integers from a file, removes any duplicate numbers, and then writes the unique numbers back to the same file in ascending order. The file 'numbers.txt' currently contains one integer per line. The developer writes the following code: with open('numbers.txt', 'r') as f: numbers = [int(line.strip()) for line in f] unique = list(set(numbers)) unique.sort() with open('numbers.txt', 'w') as f: for num in unique: f.write(str(num) + '\n') The script runs without errors, but the output file contains the numbers in descending order instead of ascending. The developer checks the sort() method and confirms it sorts in ascending order. What is the MOST likely cause of the issue?

A.The numbers were read as strings and the sort() method sorted them lexicographically, putting '10' before '2'.
B.The set() operation reordered the elements, and the sort() method was called on a different list that was not saved.
C.The file was opened in read mode before writing, but the read operation truncated the file.
D.The file was opened in append mode instead of write mode, causing the sorted numbers to be appended after the original unsorted numbers.
AnswerB

If the developer wrote unique = list(set(numbers)).sort(), unique would be None. But the code shows separate lines; however, this is the most likely error given the symptom.

Why this answer

The code snippet as shown uses unique.sort() to sort the list in-place and then writes the sorted list, so it would produce ascending order if executed exactly. The discrepancy between the expected ascending order and the reported descending order strongly suggests a deviation from the snippet, such as the developer accidentally calling sort() on a different list (for example, sorting the original numbers list or a temporary copy) and then writing the unsorted unique list. Option B captures this idea: the sort() method was called on a list that was not saved, leading to the unsorted list being written.

The other options are not consistent with the provided code: A is incorrect because the numbers are correctly converted to integers; C and D misrepresent file behavior (the file is opened in write mode, not append, and reading does not truncate the file).

Exam trap

The trap is that set() does not guarantee order, and sort() modifies the list in-place. Candidates may assume set() preserves order or that sort() returns a new list, leading them to miss the actual error if the code deviates from the snippet shown.

How to eliminate wrong answers

Option A is wrong because the code explicitly converts each line to an integer with int(line.strip()), so numbers are integers, not strings, and sort() will sort numerically, not lexicographically. Option C is wrong because opening a file in read mode does not truncate it; truncation only occurs when opening in write mode ('w') or with the 'x' flag. Option D is wrong because the code opens the file with 'w' mode, not append mode ('a'), so the sorted numbers overwrite the original content, not append to it.

58
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

Key 4 not present.

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.

59
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

The global statement allows the function to modify the global variable.

Why this answer

To modify a global variable inside a function, the global keyword must be used to declare the variable as global.

60
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

Temp is above 20, below 30.

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.

61
MCQhard

What is the output of the code in the exhibit?

A.[1, 2, 10, 20, 5]
B.[1, 10, 20, 4, 5]
C.[1, 2, 3, 10, 20, 4, 5]
D.[1, 10, 20, 3, 4, 5]
AnswerB

Correct replacement.

Why this answer

The code uses list slice assignment to replace the elements at indices 1 and 2 (the second and third elements) with the list [10, 20]. Starting from [1, 2, 3, 4, 5], after the assignment lst[1:3] = [10, 20], the list becomes [1, 10, 20, 4, 5]. This matches option B.

Exam trap

Python Institute often tests the distinction between `extend()` and `append()`, and the precise behavior of step slicing, leading candidates to mistakenly think `extend()` inserts elements at a specific position or that `[::2]` removes elements rather than selecting every second one.

How to eliminate wrong answers

Option A is wrong because it shows `[1, 2, 10, 20, 5]`, which incorrectly assumes the slice `[::2]` takes the first two elements and then appends `[10, 20]` before the last element, misunderstanding both the step slicing and the `extend()` behavior. Option C is wrong because it shows `[1, 2, 3, 10, 20, 4, 5]`, which incorrectly assumes `extend()` inserts the new list in the middle or that the slice retains all original elements. Option D is wrong because it shows `[1, 10, 20, 3, 4, 5]`, which incorrectly assumes `extend()` inserts at index 1 and that the slice only removes the second element, misrepresenting both the step slicing and the append position.

62
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

Standard list literal.

Why this answer

It uses the literal list syntax with square brackets and commas to directly create a list containing the integers 1, 2, and 3. This is the most straightforward and explicit way to define a list in Python.

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.

63
MCQmedium

While debugging a Python script, you see the following error: 'IndentationError: expected an indented block'. The code appears to be correctly indented with spaces. What is the most likely cause?

A.You used the wrong number of spaces (e.g., 2 spaces instead of 4).
B.You forgot to include a colon at the end of a compound statement.
C.The script has a logic error in the condition.
D.You mixed tabs and spaces for indentation.
AnswerD

Mixture of tabs and spaces is a common cause of IndentationError.

Why this answer

Mixing tabs and spaces for indentation is a common cause of 'IndentationError: expected an indented block' even when the code appears correctly indented. Python 3 disallows mixing tabs and spaces; it uses the exact whitespace characters to determine block structure, and inconsistent usage triggers this error.

Exam trap

The PCEP exam often tests the misconception that any indentation inconsistency (like wrong number of spaces) causes an IndentationError, when in fact Python only cares about consistency and does not enforce a specific number of spaces.

How to eliminate wrong answers

Option A is wrong because using a consistent number of spaces (e.g., 2 instead of 4) does not cause an IndentationError; Python accepts any consistent indentation width. Option B is wrong because a missing colon at the end of a compound statement (like 'if', 'for', 'def') causes a 'SyntaxError', not an 'IndentationError'. Option C is wrong because a logic error in a condition does not produce an IndentationError; it would cause incorrect runtime behavior, not a syntax-level indentation failure.

64
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

Uses context manager and iterates lazily.

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.

65
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

Reassignment creates a new local variable, leaving original untouched.

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.

66
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

This catches ValueError and allows graceful handling.

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.

67
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 domain error because sqrt of negative number is not defined in real math.

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.

68
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

For works with lists, tuples, strings, etc.

Why this answer

A `for` loop in Python is designed to iterate over any iterable sequence, such as lists, tuples, strings, dictionaries, or ranges. This is a fundamental property of the `for` loop, which retrieves each item from the sequence in order until the sequence is exhausted.

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.

69
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

Correct assignment.

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.

70
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

Because 'list' was reassigned, it no longer refers to the built-in function.

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.

71
MCQhard

A Python script uses the following code to open a file: f = open('data.txt', 'w'). The programmer then writes multiple lines to the file. After writing, which of the following is the BEST practice to ensure data integrity?

A.Call f.close() after writing.
B.Call f.flush() after writing.
C.No action needed; Python automatically closes files.
D.Use a with statement to open the file.
AnswerD

Ensures proper closing even on exceptions.

Why this answer

Using a `with` statement ensures that the file is automatically closed when the block exits, even if an exception occurs. This guarantees that all buffered data is flushed to disk, preventing data loss or corruption. It is the recommended best practice in Python for reliable file handling.

Exam trap

Python Institute often tests the misconception that Python automatically closes files or that calling `close()` or `flush()` individually is sufficient, when in fact the `with` statement is the only guaranteed way to ensure proper cleanup and data integrity.

How to eliminate wrong answers

Option A is wrong because calling `f.close()` alone does not guarantee data integrity if an exception occurs before the call; it also requires explicit management of the close operation. Option B is wrong because `f.flush()` only forces the internal buffer to be written to the operating system, but does not ensure the file is closed or that data is fully written to disk (the OS may still cache it). Option C is wrong because Python does not automatically close files; the file remains open until garbage collection, which can lead to resource leaks and potential data loss.

72
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

True, equal.

Why this answer

The equality operator '==' compares the two operands and returns True if they are equal. Since 3 is indeed equal to 3, the expression evaluates to True.

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.

73
MCQhard

Given the code: a = [1, 2, 3]; b = a; b.append(4). What is the value of a?

A.[1, 2, 3, 4]
B.Error
C.[1, 2, 3]
D.[1, 2, 3, [4]]
AnswerA

Both a and b refer to the same list.

Why this answer

In Python, variables hold references to objects, not copies. When `b = a` is executed, both `a` and `b` point to the same list object in memory. The `append()` method modifies the list in-place, so the change is visible through both references.

Thus, `a` becomes `[1, 2, 3, 4]`.

Exam trap

The trap here is that Cisco tests whether candidates understand that assignment with `=` does not create a new copy for mutable objects; many mistakenly think `b = a` creates a separate list, leading them to choose option C.

How to eliminate wrong answers

Option B is wrong because `append()` is a valid list method and does not raise an error; it modifies the list in-place and returns `None`, but the code does not assign that return value. Option C is wrong because it assumes `b = a` creates a copy of the list, but Python uses reference semantics for lists, so modifications via `b` affect `a`. Option D is wrong because `append(4)` adds the integer `4` as a single element, not as a nested list; the result is `[1, 2, 3, 4]`, not `[1, 2, 3, [4]]`.

Page 1 of 2 · 137 questions totalNext →

Ready to test yourself?

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