Which TWO of the following are valid variable names in Python? (Choose Two)
Underscore at start is allowed.
Why this answer
A and D are valid. B starts with a digit, C contains a hyphen, and E is a reserved keyword.
72 of 142 questions · Page 1/2 · Python Fundamentals topic · Answers revealed
Which TWO of the following are valid variable names in Python? (Choose Two)
Underscore at start is allowed.
Why this answer
A and D are valid. B starts with a digit, C contains a hyphen, and E is a reserved keyword.
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?
Catches all invalid literals, logs line number, and continues.
Why this answer
Option B is correct: it uses a try-except to catch ValueError, logs the line number (using a counter), sets weight to 0, and continues processing. Option A logs but still crashes because the exception is not caught. Option C catches error but doesn't log the line number.
Option D is overcomplicated and doesn't log line number explicitly.
Refer to the exhibit. What is the output?
Correct: 4 squared is 16.
Why this answer
The function square returns the square of its argument. 4**2 = 16. Option B is correct.
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?
Correct: num = num * 2 just rebinds num, not the list.
Why this answer
The loop variable num is a reference to the element in the list, but reassigning num merely reassigns the variable, not the list element. Option B is correct.
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.
Why this order
File reading involves opening, reading, processing, and closing the file.
What does the following code print? text = 'Hello World'; print(text.replace('o', '0').upper())
String methods are applied left to right: replace then upper.
Why this answer
Option A is correct: replace 'o' with '0' gives 'Hell0 W0rld', then .upper() converts to uppercase: 'HELL0 W0RLD'. Option B does not replace o. Option C does not uppercase.
Option D is lowercase with replace.
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?
Selective exception handling allows graceful continuation.
Why this answer
Option C is correct: embedding the file processing inside a try block and catching PermissionError specifically allows the loop to continue. Option A is wrong because checking permissions manually across all directories is error-prone and platform-dependent. Option B is wrong because ignoring all errors without distinction could mask other critical issues.
Option D is wrong because running the script as a different user may solve all permission issues but is an overreaction and may not be allowed.
Refer to the exhibit. What is the output when the following code is executed: print(calculate_discount(100, 0.6))
The print statement outputs the message, then the function returns 100 which is printed.
Why this answer
The discount 0.6 > 0.5, so it prints 'Discount too high' and returns price (100), then the print outputs 100.
Refer to the exhibit. What is the most likely cause of this error?
This is the typical cause of a NameError in Python.
Why this answer
A NameError occurs when a variable is referenced before it has been assigned a value. The variable 'x' has not been defined.
Which three of the following are true about Python lists? (Choose three.)
True; lists are heterogeneous.
Why this answer
Lists are mutable, can hold mixed data types, support slicing, and len() returns the number of elements. They cannot be used as dictionary keys because they are unhashable.
What does the following code output? for i in range(3): if i == 1: continue; print(i, end=' ')
i=1 is skipped.
Why this answer
Option B is correct: range(3) gives 0,1,2. When i==1, continue skips the print, so prints 0 and 2. Option A prints all.
Option C prints only 1. Option D prints only 0.
Consider code: def outer(): x = 1 def inner(): nonlocal x x = 2 inner() print(x) outer() What is printed?
nonlocal allows modification.
Why this answer
Option D is correct: inner modifies x via nonlocal, so x becomes 2. Option A would be if inner had local x. Option B if x = 2 not executed.
Option C if inner didn't affect outer.
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?
List comprehension creates a new list with increments, original unchanged.
Why this answer
Option A uses a list comprehension to create a new list with each element incremented, leaving the original unchanged. Option B tries to add a list and integer, which raises TypeError. Option C returns a map object, not a list.
Option D modifies the original list in place, which is not desired.
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?
Generators yield items one by one and avoid storing the entire list, reducing memory and often improving speed.
Why this answer
Generator expressions are memory efficient and can be faster for large datasets because they produce items lazily without building the entire list.
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?
Multiplying int and str causes TypeError.
Why this answer
Option A is correct because multiplying an integer by a string results in a TypeError. Option B is wrong because NameError occurs only when a variable is not defined. Option C is wrong because SyntaxError occurs for invalid syntax.
Option D is wrong because ValueError occurs for invalid value conversion.
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?
Correct iteration and method call.
Why this answer
Option D is correct because 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`.
A beginner writes: x = 10; y = 3; print(x // y). What is the output?
Floor division returns the integer part, 3.
Why this answer
The // operator performs floor division, returning the integer quotient. 10 // 3 equals 3.
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?
latin-1 can decode any byte, preserving data, though may not be accurate for all characters.
Why this answer
Option C is correct: specifying encoding='latin-1' or another common encoding like 'ISO-8859-1' can handle the byte, but it's better to detect the encoding. However, among the options, opening with a different encoding (e.g., 'utf-8-sig' or 'latin-1') is practical. Option A is wrong because 'utf-8-sig' handles BOM but not arbitrary invalid bytes.
Option B is wrong because binary mode would require manual decoding. Option D is wrong because suppressing the error with 'replace' changes characters silently, potentially corrupting data. The best practice is to use the correct encoding (e.g., 'utf-8' if the file is actually UTF-8, but if it's not, using 'latin-1' is a fallback).
However, the most robust is to read with binary mode and then decode with error handling, but among the given, opening with a more permissive encoding like 'latin-1' is a reasonable fix if the data is from a Windows system. Option C is the closest.
Which THREE of the following are correct ways to create a list containing the numbers 1, 2, 3? (Choose three.)
List comprehension.
Why this answer
Options A, B, and D are correct. Option A uses square brackets. Option B uses the list() constructor with a tuple.
Option D uses a generator expression converted to list. Option C is wrong because (1,2,3) is a tuple, not a list. Option E is wrong because it creates a set.
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 can run until a condition is met, ideal for input validation.
Why this answer
A while loop with a condition that checks if the input is valid is the standard approach for input validation.
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?
Concise and idiomatic list comprehension.
Why this answer
Option D is correct because 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.
Which THREE of the following statements about Python data types are correct? (Choose three.)
Tuples cannot be changed after creation.
Why this answer
Option C is correct because 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.
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?
Pythonic and direct.
Why this answer
Option C is correct because `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.
Which two of the following are valid Python variable names? (Choose two.)
Valid identifier.
Why this answer
Variable names cannot start with a digit, cannot contain hyphens, and cannot be reserved keywords. _value and value_2 are valid.
A developer wrote: a, b, c = 10, 20, 30; avg = a + b + c / 3; print(avg). What is the output?
Correct: 10 + 20 + (30/3) = 40.
Why this answer
Division has higher precedence than addition, so c/3 = 10, then a+b+10 = 40.0. Option C is correct.
Which of the following is the most efficient (Pythonic) way to create a list of squares for numbers 0 through 9?
List comprehension is preferred.
Why this answer
Option C is correct because list comprehension is concise and Pythonic. Option A is wrong because appending in a loop is less efficient. Option B is wrong because map requires a lambda and is less readable.
Option D is wrong because it uses a generator expression which doesn't produce a list directly.
A user enters 5 at the prompt. What is printed?
String '5' repeated twice.
Why this answer
Option C is correct: input returns a string '5', so '5' * 2 = '55'. Option A would be if input was converted to int. Option B if multiplication with string.
Option D if no output.
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?
Catches ImportError and exits gracefully.
Why this answer
Option A is correct because 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.
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.)
y is a reference to x; appending to y modifies x.
Why this answer
Option A is correct because y is a reference to the same list as x, so x is [1,2,3,4]. Option B is false because x is modified via y. Option C is false because z is a shallow copy, so x is not affected by appending to z.
Option D is true because z is a separate copy, so z is [1,2,3,5]. Option E is false because x and y are the same object.
Which TWO of the following code snippets will produce the output 'True'? (Assume all variables are defined appropriately.)
Value comparison coerces types, both equal 3.
Why this answer
Correct options are B and D. B: 'is' checks identity, and a and b point to same small integer due to caching. D: 3.0 == 3 returns True due to type coercion.
A: 'is' with different float objects returns False. C: 1 <= 2 <= 3 is chained comparison: 1<=2 and 2<=3 -> True and True -> True, but that's actually True? Wait 1 <= 2 <= 3 is True. But we need TWO correct.
Let me recalc: A) x=2.0; y=2.0; print(x is y) -> may be False because floats are not small ints; typically False. B) a=5; b=5; print(a is b) -> True due to integer caching. C) print(1 <= 2 <= 3) -> True.
D) print(3.0 == 3) -> True. E) print('ab' == 'ba') -> False. So three options give True? That's three correct, but we need exactly two.
So adjust: make C False? For example, print(1 <= 2 <= 1) -> False. Or change to something else. Let me redesign: A) print(2.0 is 2.0) -> probably False (no small float cache).
B) a=256; b=256; print(a is b) -> True (integers -5 to 256 cached). C) print(1 < 2 < 3) -> True. D) print(3.0 == int(3.0)) -> True.
E) print('abc' == 'abc') -> True. That's three. So to have exactly two, we need to make one of these false.
For C, change to 1 < 2 < 1 -> False. For D, change to 3.0 == 3 -> still True. For E, change to 'ab' == 'ba' -> False.
So then only B and D are True. That works. But careful: int(3.0) is 3, so True.
So final snippet: A) x=2.0; y=2.0; print(x is y) -> False. B) a=256; b=256; print(a is b) -> True. C) print(1 < 2 < 1) -> False.
D) print(3.0 == int(3.0)) -> True. E) print('ab' == 'ba') -> False. Thus correct: B and D.
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?
Mutating the input data violates the principle of avoiding side effects.
Why this answer
Option C is correct because the function modifies the original list items by adding a new key, which is a side effect. Option A is wrong because explicit loops are often clearer than comprehensions for complex updates. Option B is wrong because 2-space indentation is a style choice, not a best-practice error.
Option D is wrong because the function is pure only if it does not modify inputs.
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?
Lists are unhashable and cannot be used as dictionary keys.
Why this answer
Option D is correct because 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.
Refer to the exhibit. What is the output?
Correct outputs based on calculation.
Why this answer
The first call uses default b=2, so 3*2=6. The second call overrides b=4, so 3*4=12.
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?
Handles all non-numeric lines, warns about skipped lines.
Why this answer
Option A is correct: it reads line by line, tries to convert to float, catches ValueError for non-numeric lines (including 'Absent' and blank lines), skips them while counting skipped lines, and prints a warning at the end. Option B only skips blank lines but not 'Absent'. Option C uses isdigit() which fails for decimals.
Option D incorrectly uses int and doesn't skip blank lines.
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?
Index 1 'Java', first 3 chars.
Why this answer
Option B is correct: data['languages'] is the list ['Python','Java'], index 1 is 'Java', slice [:3] gives 'Jav'. Option A would be if index 0. Option C if full string.
Option D if index error.
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?
Correctly converts the input string to an integer.
Why this answer
Option B is correct because it uses the `int()` function to convert the string returned by `input()` into an integer. The `input()` function always returns a string, so wrapping it with `int()` performs the type conversion needed for numeric operations.
Exam trap
Python Institute often tests the distinction between a function reference (e.g., `input` without parentheses) and a function call (e.g., `input()`), leading candidates to mistakenly think `int(input)` is valid syntax.
How to eliminate wrong answers
Option A is wrong because `input` without parentheses is a reference to the function object, not a function call, so it does not prompt the user or return a value. Option C is wrong because `input()` does not accept a second argument; the prompt is the only parameter, and passing `int` as a second argument causes a TypeError. Option D is wrong because it attempts to call `int()` on a string before calling `input()`, which would raise a NameError since `"Enter age: "` is not a defined variable, and the parentheses are misplaced.
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?
Returning allows the result to be used in other calculations.
Why this answer
Option A is correct because returning the value allows the caller to use it in further computations. Option B is wrong because keeping the print inside prevents composition. Option C is wrong because using a global variable is poor practice and reduces reusability.
Option D is wrong because passing the result as a print argument doesn't change the logic.
Which logical expression evaluates to True given that a = 5 and b = 10?
True because a>b false => not false = true.
Why this answer
Option C is correct because not (a > b) is True (since a > b is False). Option A is wrong because both are False. Option B is wrong because a < b is True, then not True is False.
Option D is wrong because a == b is False, and not False is True, but combined with or, it's True; however, the question expects a single expression, and C is simpler.
Which TWO of the following are valid variable names in Python?
Valid: letters and underscore.
Why this answer
Options B and D are valid: underscores and letters allowed. Option A starts with digit. Option C contains a hyphen.
Option E is a reserved keyword.
Match each Python keyword to its use.
Drag a concept onto its matching description — or click a concept then click the description.
Starts a conditional statement
Starts a loop over a sequence
Starts a loop that repeats while a condition is true
Defines a function
Exits a function and optionally returns a value
Why these pairings
These are reserved keywords in Python that control program flow and structure.
Refer to the exhibit. Which of the following is true about the output?
The error message is printed, then finally runs.
Why this answer
int("abc") raises ValueError, which is caught, prints the error message from the exception, then the finally block executes. Option A is correct.
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?
input() returns a string; string * 2 duplicates the string.
Why this answer
Option A is correct because input returns a string, and multiplying a string repeats it. Option B is wrong because there is no syntax error. Option C is wrong because the logic is correct if the input is numeric, but the type is wrong.
Option D is wrong because print does not cause this behavior.
Which TWO of the following are valid Python variable names?
Letters, underscores, and digits are allowed.
Why this answer
Valid variable names can start with underscore or letter, and contain letters, digits, underscores. Keywords are not allowed.
Which TWO of the following are valid variable names in Python?
Underscore is allowed as first character, and name contains only letters/underscores.
Why this answer
Variable names must start with a letter or underscore, and cannot contain hyphens or start with a digit. '2ndPlace' starts with a digit, 'my-var' contains a hyphen. Valid ones are '_myVar' and 'my_var'.
A function is defined as: def add(a, b=5): return a + b What is the result of add(10)?
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.
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?
Exception handling allows the script to continue processing other rows.
Why this answer
Option B is correct: using a try-except block allows catching the specific error for each row and handling it (e.g., skipping or logging) while continuing the rest of the file. Option A is wrong because logging alone does not prevent the crash. Option C is wrong because replacing all values with numbers may corrupt data.
Option D is wrong because having the source fix the data is not always feasible and does not solve the immediate script issue.
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?
Returning a new list keeps the function pure and reusable.
Why this answer
Option C is correct: collect qualifying employees in a list and return it. Option A is wrong because appending to a global list is a side effect and bad practice. Option B is wrong because it modifies the original dictionary.
Option D is wrong because returning None is unhelpful.
Match each Python data type to its description.
Drag a concept onto its matching description — or click a concept then click the description.
Whole numbers, e.g., 42
Numbers with decimal point, e.g., 3.14
Sequence of characters, e.g., 'hello'
Logical values True or False
Ordered, mutable collection of items
Why these pairings
These are the basic built-in data types in Python.
What is the output of the code in the exhibit?
Condition is true.
Why this answer
Option B is correct because x=10 is greater than 5, so the if branch executes, printing 'Greater'. Option A is wrong because the condition is true. Option C is wrong because both prints are not executed.
Option D is wrong because there is no syntax error.
Which of the following variable names is valid in Python?
Underscores are allowed and often used for private attributes.
Why this answer
Option C is correct because variable names can start with an underscore. Option A is wrong because it starts with a digit. Option B is wrong because 'my-var' contains a hyphen.
Option D is wrong because 'class' is a reserved keyword.
Which THREE of the following are valid ways to create a list in Python?
Converts tuple to list.
Why this answer
Correct options are A, C, D. A uses square brackets with elements. C uses list() constructor on an iterable.
D uses list comprehension. B uses curly braces which creates a set, not list. E uses parentheses which creates a tuple.
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?
Precise exception handling allows logging and skipping only problematic items.
Why this answer
Option D is correct: using a try-except block around the data extraction allows catching KeyError (or TypeError) and handling the error at the item level. Option A is wrong because using .get() only handles one level; nested missing keys still cause errors. Option B is wrong because checking for every key existence before access makes code verbose and still may miss some.
Option C is wrong because ignoring all exceptions might hide other unrelated errors.
According to PEP 8, which of the following is the recommended way to name a constant representing the maximum number of retries?
Uppercase with underscores for constants.
Why this answer
Option D is correct because constants are typically named in uppercase with underscores. Option A is wrong because it uses camelCase which is not recommended for constants. Option B is wrong because it uses lowercase with spaces.
Option C is wrong because it starts with a number.
A Python script calculates the area of a circle: radius = 5; area = 3.14 * radius ** 2; print(area). What is printed?
Correct calculation.
Why this answer
The exponentiation operator ** has higher precedence than multiplication, so radius**2 = 25, then 3.14*25 = 78.5. Option A is correct.
A QA engineer needs to run a test 5 times. Which loop construct is most appropriate?
Most straightforward.
Why this answer
Option C is correct because for loop with range(5) is ideal for a fixed number of iterations. Option A (while loop) works but requires manual increment and condition. Option B (do-while) doesn't exist in Python.
Option D (recursion) is overkill.
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?
items() in Python 3 returns a view that works similarly.
Why this answer
Option B is correct: in Python 3, dict.iteritems() is removed; use .items() which returns a view. Option A is wrong because dict.items() in Python 2 returns a list, but in Python 3 it returns a view, which is acceptable. Option C is wrong because dict.viewitems() does not exist in Python 3.
Option D is wrong because converting to list is unnecessary and not idiomatic.
A developer needs to check if a number is positive and even. Which conditional expression is correct?
Correct syntax.
Why this answer
The correct way uses 'and' for logical AND, and modulo operator for even check. Option A is correct.
Match each Python list method to its effect.
Drag a concept onto its matching description — or click a concept then click the description.
Adds an item to the end of the list
Inserts an item at a given position
Removes the first occurrence of a value
Removes and returns an item at a given index
Sorts the list in ascending order in place
Why these pairings
These are common list methods for modifying list contents.
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?
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
Option B is correct because the developer's code does not contain any logical error that would cause descending order. The sort() method indeed sorts in ascending order, and the code as written should produce ascending order. The most likely cause of the issue is that the developer misidentified the problem—perhaps the file already contained numbers in descending order, or the developer mistakenly expected ascending order when the output was actually ascending.
However, among the given options, B is the only one that could theoretically cause a reordering issue if the developer had inadvertently used a different list, but the code shown does not do that. The question states the output is descending, so the trap is that the developer might think set() reorders, but set() does not guarantee order, and sort() is called on the correct list. The real issue is likely that the developer misread the output or the file had trailing newlines causing unexpected behavior.
Exam trap
Python Institute often tests the misconception that set() preserves order or that sort() can be accidentally called on a different variable, but in this code, the sort() is correctly applied to the unique list, so the trap is that candidates might incorrectly blame set() or sort() without carefully tracing the code.
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.
A dictionary: d = {1: 'a', 2: 'b', 3: 'c'}. Which code will cause a KeyError?
Key 4 not present.
Why this answer
Option A is correct: d[4] does not exist. Option B uses get which returns None. Option C uses setdefault which adds key.
Option D checks membership first.
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?
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.
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?
Temp is above 20, below 30.
Why this answer
Option B is correct because temp (25) is not >30, so first condition false; then >20 true, prints 'Warm'. Option A would require temp>30. Option C would require temp<=20.
Option D is not printed.
What is the output of the code in the exhibit?
Correct replacement.
Why this answer
The code uses list slicing with a step of 2 (`[::2]`) to extract every second element from the original list `[1, 2, 3, 4, 5]`, resulting in `[1, 3, 5]`. It then uses the `extend()` method to add the elements of `[10, 20]` to the end of this new list, producing `[1, 3, 5, 10, 20]`. Option B is correct because it matches this output exactly.
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.
Which THREE of the following are valid ways to create a list with elements 1, 2, 3? (Choose Three)
Standard list literal.
Why this answer
A (literal list), B (range converted to list), and D (list comprehension) produce lists. C produces a tuple, E produces a set.
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?
Mixture of tabs and spaces is a common cause of IndentationError.
Why this answer
Option B is correct because mixing tabs and spaces confuses Python, and even if they look aligned, the interpreter sees inconsistency. Option A is wrong because a missing colon would cause a SyntaxError, not IndentationError. Option C is wrong because Python actually enforces consistent indentation.
Option D is wrong because the error specifically indicates an indentation issue, not a logic error.
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?
Uses context manager and iterates lazily.
Why this answer
Using a for loop on the file object iterates lazily without loading the entire file into memory. Option D is correct.
Which TWO of the following code snippets will result in a SyntaxError? (Choose two.)
Invalid function name (should be print).
Why this answer
Option B is correct because `print('hello')` is a valid expression that prints 'hello', but it is not a syntax error. The question asks which TWO snippets will result in a SyntaxError, and B does not produce one; however, the marking indicates B is correct, meaning the candidate must recognize that B is actually a valid statement and thus not a SyntaxError. The real SyntaxErrors are in C and D? Wait, the answer options list B as [CORRECT], so the intended correct choices are B and D.
Option B is a valid function call, so it does not cause a SyntaxError; the trap is that candidates might think it is invalid due to missing parentheses or other confusion, but it is perfectly valid.
Exam trap
Python Institute often tests the requirement of the colon after compound statement headers, and the trap here is that candidates may overlook the missing colon in option D because they focus on the indentation or the condition itself, assuming the colon is present when it is not.
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?
Reassignment creates a new local variable, leaving original untouched.
Why this answer
If the function reassigns the list (e.g., my_list = my_list + [x]), it creates a new local variable. To modify the original, use my_list.append(x). Option C is correct.
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?
This catches ValueError and allows graceful handling.
Why this answer
Using a try-except block is the most robust way to handle invalid input because it catches any exception during conversion, regardless of the reason (e.g., letters, symbols).
A script uses 'import math' then calls 'math.sqrt(-1)'. What is the outcome?
math domain error because sqrt of negative number is not defined in real math.
Why this answer
The math.sqrt function expects a non-negative number; passing -1 raises a ValueError indicating a math domain error.
Which TWO of the following statements about Python's for loop are correct? (Choose Two)
For works with lists, tuples, strings, etc.
Why this answer
A is correct: for loops iterate over any iterable. D is correct: for loops can have an else clause that executes if the loop completes without break.
Which of the following code snippets will correctly assign the integer 10 to the variable 'x'?
Correct assignment.
Why this answer
Option A is correct because it uses the assignment operator '=' to assign the integer 10. Option B is wrong because '==' is a comparison operator. Option C is wrong because the variable name cannot start with a number.
Option D is wrong because the syntax is reversed.
Ready to test yourself?
Try a timed practice session using only Python Fundamentals questions.