CCNA Python Fundamentals Questions

67 of 142 questions · Page 2/2 · Python Fundamentals topic · Answers revealed

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

77
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

Option D is correct because 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.

78
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

Option C is correct because 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.

79
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

Option A is correct because 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]]`.

80
Multi-Selectmedium

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

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

Immutable: string objects cannot be changed.

Why this answer

Correct options are B and D: integers are immutable, tuples are immutable. Lists and dictionaries are mutable. Strings are immutable but not in options? Wait: options A-E: A) list, B) int, C) dict, D) tuple, E) set? Actually I need to provide 5 options.

Let me define: A) list, B) dict, C) tuple, D) str, E) int. That covers. Actually typical PCEP: int, float, bool, str, tuple are immutable; list, dict, set mutable.

So pick two immutables: tuple and int? Or str and int? I'll do B (tuple) and D (str). But careful: which TWO? Let's set options: A) list, B) tuple, C) dict, D) str, E) int. Correct: B and D (tuple and str) or B and E? Actually str is immutable, int is immutable.

Both are correct. I need exactly TWO correct. I'll choose B and D as correct, but then E is also correct? That would be three.

So better to only have two correct. Let's pick options where only two are immutable. Common immutable: int, float, bool, str, tuple, bytes, frozenset.

So I'll set: A) list, B) tuple, C) dict, D) set, E) str. Then immutables: tuple and str. So correct: B and E.

That works. Explanation: B (tuple) and E (str) are immutable; others mutable.

81
Multi-Selectmedium

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

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

Trailing comma allowed.

Why this answer

Option A is correct because Python allows an optional trailing comma after the last element in a list literal, so `[1, 2, 3,]` is syntactically valid and creates the list `[1, 2, 3]`. This is a common feature in Python that helps with version control diffs when adding or removing elements.

Exam trap

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

82
MCQhard

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

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

NameError occurs when variable is not defined.

Why this answer

Option C is correct because the variable 'result' is not defined before the print call. Option A is wrong because if result were missing a print function, the error would be different. Option B is wrong because a typo in a variable name would produce a NameError but it's not likely 'result' misspelled.

Option D is wrong because import error would be ImportError.

83
MCQmedium

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

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

Cannot concatenate str and int.

Why this answer

Python does not allow concatenation of string and integer; it raises a TypeError.

84
MCQhard

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

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

Correct: **kwargs accepts arbitrary keyword arguments.

Why this answer

The **kwargs syntax collects all keyword arguments into a dictionary. Option A is correct.

85
MCQhard

Refer to the exhibit. What is printed?

A.None
B.x greater
C.equal
D.y greater
AnswerB

The if condition is satisfied.

Why this answer

The condition x > y is True (10 > 5), so the first branch executes and prints 'x greater'.

86
MCQhard

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

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

This reads each line as needed, keeping memory usage low.

Why this answer

Processing the file line by line using a for loop reads only one line at a time into memory, making it efficient for large files and preventing memory exhaustion.

87
MCQhard

Refer to the exhibit. A developer runs this code. What is printed?

A.Running in normal mode
B.Error
C.True
D.Debug mode active
AnswerA

Since debug is False, the else branch runs.

Why this answer

config.get('debug', False) returns False because the key 'debug' exists with value False. The condition is False, so the else branch prints 'Running in normal mode'.

88
Multi-Selectmedium

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

Select 3 answers
A.float
B.list
C.char
D.dict
E.record
AnswersA, B, D

Built-in numeric type.

Why this answer

A is correct because `float` is a built-in Python numeric data type used to represent floating-point numbers (e.g., 3.14, -0.001). It is one of the core immutable types in Python, distinct from integers and complex numbers.

Exam trap

Python Institute often tests the distinction between Python's built-in types and types from other languages (like `char` or `record`) to catch candidates who assume Python has a dedicated character type or who confuse database terminology with Python data structures.

89
Multi-Selecteasy

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

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

Valid.

Why this answer

Option B (my_var) is correct because Python variable names can contain letters, digits, and underscores, but must not start with a digit. 'my_var' follows all naming rules: it starts with a letter, uses an underscore, and contains no invalid characters.

Exam trap

Python Institute often tests the rule that hyphens are invalid in variable names (tricking candidates who confuse them with underscores) and that keywords like 'class' cannot be used as identifiers, even though they look like valid names.

90
MCQhard

What is the output of the following code? x = [1, 2, 3]; y = x; y.append(4); print(x)

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

x and y refer to the same list, so the append affects both.

Why this answer

Assignment y = x creates a reference to the same list object, not a copy. Modifying y also modifies x. Therefore, x becomes [1,2,3,4].

91
MCQeasy

The exhibit shows a JSON configuration. Which Python data structure is best suited to represent this configuration?

A.Dictionary
B.Tuple
C.String
D.List
AnswerA

Key-value pairs match JSON.

Why this answer

Option A is correct because JSON objects map directly to Python dictionaries. Option B is wrong because a list would require indices. Option C is wrong because a tuple is immutable.

Option D is wrong because a string would lose structure.

92
MCQhard

Consider the code: x = 10; def func(): x = 5; print(x); func(); print(x). What is the output?

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

Local scope inside function, global unchanged outside.

Why this answer

Option D is correct: inside function, local x=5 shadows global x=10, so prints 5; after function, global x is still 10, so prints 10. Option A would happen if global x changed. Option B if both printed 5.

Option C if both printed 10.

93
MCQmedium

A developer writes a function that returns multiple values. How should they return these values?

A.return a, b
B.return a+b
C.return [a,b]
D.return a; return b
AnswerA

This returns a tuple containing a and b.

Why this answer

In Python, returning multiple values separated by commas automatically packs them into a tuple, which is the standard way.

94
MCQmedium

Consider the following function definition: def add(a, b): return a + b What is the value of add(3, '4')?

A.Error due to missing import
B.'34'
C.7
D.TypeError: unsupported operand type(s) for +: 'int' and 'str'
AnswerD

Incompatible types.

Why this answer

Option D is correct because adding an int and a str raises a TypeError. Option A is wrong because it would require implicit conversion. Option B is wrong because concatenation works with strings only.

Option C is wrong because Python does not auto-convert.

95
MCQeasy

Refer to the exhibit. What is the output?

A.Invalid integer\nSome error
B.No output
C.Some error
D.Invalid integer
AnswerD

The specific ValueError handler runs.

Why this answer

int("hello") raises ValueError, which is caught by the first except block, printing 'Invalid integer'.

96
MCQeasy

Which of the following is the correct way to define a function that takes no arguments and returns the value 42?

A.function f(): return 42
B.def f(): return 42
C.def f: return 42
D.def f(): return 42
AnswerD

Correct syntax for a function that returns 42.

Why this answer

Option D is correct because in Python, a function is defined using the `def` keyword, followed by the function name, parentheses (even for no arguments), a colon, and the body with `return 42`. This syntax is required by the Python language specification.

Exam trap

Python Institute often tests the requirement for empty parentheses in function definitions, trapping candidates who think they can omit them when no arguments are needed.

How to eliminate wrong answers

Option A is wrong because Python uses the `def` keyword, not `function`, to define functions. Option B is wrong because it is identical to D but lacks the [CORRECT] marker; however, the question lists D as correct, so B is not the intended answer. Option C is wrong because it omits the parentheses `()` after the function name, which are mandatory even when the function takes no arguments.

97
MCQmedium

A programmer writes: x = 5; y = 2; result = x / y. What is the type of result?

A.int
B.float
C.str
D.complex
AnswerB

True: / operator returns float.

Why this answer

In Python 3, the division operator (/) always returns a floating-point number, even if both operands are integers. Since x and y are both integers (5 and 2), the result of 5 / 2 is 2.5, which is of type float. Therefore, option B is correct.

Exam trap

Python Institute often tests the distinction between Python 3's true division (/) and floor division (//), trapping candidates who assume integer division returns an integer like in Python 2 or other languages such as C or Java.

How to eliminate wrong answers

Option A is wrong because the division operator (/) in Python 3 never returns an int; it always returns a float, even when the division is exact (e.g., 4 / 2 returns 2.0). Option C is wrong because the result of a numeric division is a numeric type, not a string; a string would require explicit conversion or string concatenation. Option D is wrong because complex numbers are created using a literal like 3+4j or the complex() function, not from integer division.

98
MCQeasy

What function is used to read input from the user in Python 3?

A.read_input()
B.sys.stdin.readline()
C.input()
D.raw_input()
AnswerC

Standard for user input.

Why this answer

Option C is correct because input() reads a string from stdin. Option A is wrong because raw_input() is Python 2. Option B is wrong because read_input() does not exist.

Option D is wrong because sys.stdin.readline() works but is not the standard simple function.

99
Multi-Selectmedium

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

Select 2 answers
A.for
B.var123
C.my-var
D.1var
E._myVar
AnswersB, E

Valid: letters and digits.

Why this answer

Option B (var123) is correct because Python variable names must start with a letter or underscore, and can contain letters, digits, or underscores. 'var123' starts with a letter and contains only valid characters, making it a legal identifier.

Exam trap

Python Institute often tests the rule that hyphens are not allowed in variable names, tricking candidates who are used to hyphenated names from other languages like HTML or CSS.

100
MCQeasy

Which of the following statements about Python indentation is true?

A.Indentation is optional but recommended.
B.You can mix tabs and spaces freely.
C.Indentation must be consistent within a block.
D.Indentation only matters for loops and conditionals.
AnswerC

Correct.

Why this answer

Option C is correct because Python enforces consistent indentation within a block to define the scope of statements. Unlike many languages that use braces, Python relies on the indentation level to group statements, and any inconsistency (e.g., mixing spaces and tabs or varying the number of spaces) will raise an IndentationError.

Exam trap

The trap here is that candidates often think indentation is merely a style recommendation (like in other languages) or that it only applies to control flow statements, but Python strictly enforces it for all block structures, and mixing tabs with spaces is a common pitfall that leads to runtime errors.

How to eliminate wrong answers

Option A is wrong because indentation is not optional in Python; it is syntactically mandatory to define code blocks, and omitting it will cause a syntax error. Option B is wrong because mixing tabs and spaces is not allowed; Python 3 disallows this and will raise a TabError due to ambiguity in indentation levels. Option D is wrong because indentation matters for all compound statements, including function definitions, class definitions, try/except blocks, and with statements, not just loops and conditionals.

101
MCQhard

Given the code: my_list = [1, 2, 3, 4, 5]. What is the output of print(my_list[-3:-1])?

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

Negative indices: -3 corresponds to index 2 (value 3), -1 corresponds to index 4 (value 5) but stop exclusive, so indices 2 and 3: [3,4].

Why this answer

Option B is correct because slicing with negative indices: -3 is index 2 (value 3), -1 is index 4 (value 5) but stop is exclusive, so elements at indices 2 and 3 are included, i.e., [3,4]. Option A gives [2,3] which is slice from -4 to -2. Option C is [3,4,5] which is -3:.

Option D is [4,5] which is -2:.

102
MCQeasy

A junior developer writes a Python script to calculate the average of three numbers: avg = a + b + c / 3. What is the problem with this code?

A.Division by a variable is not allowed
B.Missing parentheses cause incorrect order of operations
C.Python cannot divide integers
D.Variable names are too short
AnswerB

Division has higher precedence than addition, so parentheses are needed to group the sum.

Why this answer

Due to operator precedence, division occurs before addition, so the formula computes a + b + (c/3) instead of (a+b+c)/3.

103
MCQmedium

A developer wants to extract the file extension from a filename: 'report.pdf'. Which string method will return 'pdf'?

A.'report.pdf'.replace('.', '')
B.'report.pdf'.split('.')[-1]
C.'report.pdf'.split('.')[1]
D.'report.pdf'.removeprefix('report.')
AnswerB

Returns 'pdf'.

Why this answer

Option A is correct: split('.') splits at dot and [-1] gets last element. Option B splits at dot and [1] works if there is exactly one dot. Option C replaces dot with empty string, not extraction.

Option D removes prefix 'report.', not suffix.

104
MCQmedium

A programmer writes the following code: if x > 5: print('Greater') What is the most likely cause of an IndentationError?

A.The print statement is not indented.
B.The comparison operator is wrong.
C.The variable x is undefined.
D.The colon after the condition is missing.
AnswerA

Requires indentation.

Why this answer

Option B is correct because the print statement must be indented to be inside the if block. Option A is wrong because the colon is correct. Option C is wrong because the condition is valid.

Option D is wrong as it's a syntax error, not runtime.

105
Multi-Selecthard

Which TWO statements correctly describe Python's dynamic typing?

Select 2 answers
A.Variable types must be declared before use.
B.Python checks types only at compile time.
C.A variable's type is fixed once assigned.
D.The interpreter infers the type from the assigned value.
E.The type of a variable can change at runtime.
AnswersD, E

The type is determined by the object assigned to the variable.

Why this answer

Dynamic typing means variable types are inferred at runtime and can change. Types are not checked at compile time.

106
Multi-Selectmedium

Which TWO statements about Python lists are true?

Select 2 answers
A.Lists preserve the order of elements.
B.Lists have a fixed size once created.
C.Lists can be modified after creation.
D.Lists are immutable.
E.All elements in a list must be of the same type.
AnswersA, C

Lists are ordered.

Why this answer

Option A is correct because Python lists are ordered collections that maintain the insertion order of elements. This means the sequence in which items are added is preserved, and you can access them by their index positions.

Exam trap

Python Institute often tests the misconception that lists are immutable or fixed-size, confusing them with tuples or arrays in other languages, and also tests the false assumption that all elements must be of the same type.

107
MCQmedium

What is the output of the code in the exhibit?

A.TypeError
B.'105'
C.105
D.15
AnswerA

Cannot concatenate str and int.

Why this answer

The code attempts to concatenate a string ('10') and an integer (5) using the + operator. In Python, the + operator does not implicitly convert types; it raises a TypeError because it cannot determine whether to perform string concatenation or integer addition. This is a fundamental rule of Python's strong typing system.

Exam trap

Python Institute often tests the misconception that Python will automatically convert types (like JavaScript or PHP do), leading candidates to expect either concatenation or addition instead of recognizing that Python raises a TypeError for incompatible operand types.

How to eliminate wrong answers

Option B is wrong because it assumes Python would implicitly convert the integer 5 to a string and concatenate, producing '105', but Python raises a TypeError instead of performing implicit type coercion. Option C is wrong because it assumes Python would implicitly convert the string '10' to an integer and add, producing 105, but Python does not allow implicit conversion of strings to integers in this context. Option D is wrong because it assumes the string '10' is treated as the integer 10 and added to 5 to get 15, but Python does not perform implicit type conversion for the + operator between a string and an integer.

108
MCQmedium

A developer writes a Python script that calculates the average of a list of numbers. The script sometimes produces a ZeroDivisionError. Which of the following is the MOST appropriate way to handle this error to keep the script running?

A.Check if len(numbers) == 0 before division and skip calculation if true.
B.Use an if statement to check if the list is empty and print a warning message.
C.Remove the last element from the list if it is empty.
D.Wrap the division in a try/except block and catch ZeroDivisionError, then set the average to 0.
AnswerD

Handles the error gracefully and allows continuation.

Why this answer

Option D is correct because it uses a try/except block to catch the ZeroDivisionError specifically, which is the most robust and Pythonic way to handle runtime errors. This approach keeps the script running by setting the average to 0 when the list is empty, without relying on pre-checks that might miss other causes of division by zero (e.g., if the sum is 0 but the list is not empty). In Python, exception handling is preferred for error-prone operations like division, as it separates normal logic from error handling cleanly.

Exam trap

Python Institute often tests the distinction between error prevention (e.g., if-checks) and error handling (e.g., try/except), where candidates mistakenly choose a pre-check that only partially addresses the error, while the correct answer uses exception handling to cover all cases.

How to eliminate wrong answers

Option A is wrong because checking len(numbers) == 0 before division only prevents the error for empty lists, but a ZeroDivisionError can also occur if the divisor is zero due to other reasons (e.g., a calculated denominator), making this approach incomplete. Option B is wrong because printing a warning message does not prevent the ZeroDivisionError from occurring; the script would still crash unless the division is skipped or handled. Option C is wrong because removing the last element from an empty list raises an IndexError, not a ZeroDivisionError, and it does not address the root cause of the division by zero.

109
MCQeasy

Which of the following is an immutable data type in Python?

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

Tuples are immutable.

Why this answer

A tuple is immutable because once created, its elements cannot be changed, added, or removed. This is enforced by Python's internal structure: tuples are stored as a fixed-length array of object references, and no methods exist to modify them in place.

Exam trap

Python Institute often tests the misconception that 'immutable' means the variable cannot be reassigned, when in fact it means the object's contents cannot be changed — a common trap that leads candidates to incorrectly label strings or tuples as mutable.

How to eliminate wrong answers

Option B is wrong because a set is mutable — you can add or remove elements using methods like add() and discard(). Option C is wrong because a list is mutable — you can modify, append, or delete elements via indexing, append(), or pop(). Option D is wrong because a dict is mutable — you can add, update, or delete key-value pairs using assignment or methods like pop() and update().

110
Multi-Selectmedium

Which THREE of the following are built-in Python data types?

Select 3 answers
A.tuple
B.array
C.list
D.set
E.dictionary
AnswersA, C, D

tuple is a built-in immutable sequence type.

Why this answer

list, tuple, and set are built-in data types. array is from the array module, and dictionary is not a type name (the type is dict).

111
MCQhard

A system administrator is automating server configuration using Python. She has a dictionary: config = {'host': 'localhost', 'port': 8080, 'debug': True}. She needs to add a new key 'timeout' with value 30 if it does not already exist, but only if the 'debug' key is False. If 'debug' is True, she should not add 'timeout'. Additionally, she wants to ensure that the ordering of keys in the dictionary remains stable (insertion order). Which code snippet correctly implements this logic?

A.if not config.get('debug'): config.setdefault('timeout', 30)
B.if config.get('debug') == False: config.update({'timeout': 30})
C.if config['debug']: config['timeout'] = 30 else: pass
D.if config.setdefault('debug', False) == False: config['timeout'] = 30
AnswerA

setdefault adds key only if missing, and condition checks debug is False.

Why this answer

Option A uses setdefault with a condition; setdefault only adds if key is missing, and the condition ensures it's added only when debug is False. Option B adds timeout when debug is True, opposite of requirement. Option C uses update, which adds or overwrites, but condition is correct; however, update does not check existence first, so if timeout already exists, it would overwrite, but requirement says 'if it does not already exist', setdefault is more appropriate.

Option D's use of setdefault on 'debug' returns its value (True) so condition false, but also setdefault would add 'debug' key if missing, which is not intended. Thus A is best.

112
MCQhard

You are a developer in a financial firm. Your team is building a Python module that performs complex calculations on large datasets. To improve performance, you are using list comprehensions and built-in functions. Your code passes all unit tests, but during integration testing, the memory usage spikes unexpectedly. The problematic area is a function that constructs a large list of intermediate results using a list comprehension that references a generator. The code is: def process(data): results = [expensive_transform(x) for x in data] # further processing on results You suspect that the list comprehension stores all results in memory at once, but you need to keep the function's output as a list for subsequent operations. What is the best solution to reduce memory without changing the function's return type?

A.Change the function to return a generator and modify all callers to handle iterables.
B.Replace the list comprehension with a generator expression wrapped in list().
C.Use a for loop with the .append() method instead of comprehension.
D.Increase the system's available memory via configuration.
AnswerA

Avoids building the full list if subsequent processing can consume lazily.

Why this answer

Option A is correct: the generator expression creates items on the fly, but then list() consumes it to produce a list, still holding all in memory. So no improvement. Option B is correct: a loop with list.append is memory-equivalent to a list comprehension.

Option C is correct: changing to a generator only postpones the problem because later operations require a list. Option D is the correct approach: lazily produce results using a generator, and only convert to list at the very end if necessary. If the subsequent processing can also work with an iterator, you can avoid the list entirely.

The best solution is to change the whole processing pipeline to use iterators, not just one part.

113
Multi-Selecthard

Which THREE of the following will correctly iterate over all keys and values of a dictionary d = {'a':1, 'b':2}?

Select 3 answers
A.for i, k in enumerate(d):
B.for k in d: print(d[k])
C.for v in d.values(): print(v) -- only values
D.for k, v in d.items():
E.for k in d.keys(): print(d[k])
AnswersB, D, E

Default iteration over keys.

Why this answer

Options B, C, D are correct. B: items() returns key-value pairs. C: keys() with index d[k] works.

D: direct iteration over dictionary gives keys. A is wrong: enumerate on dict gives index, not key. E is wrong: values() gives only values.

114
MCQmedium

A programmer wants to iterate over a list and also access the index. Which built-in function should they use?

A.zip()
B.map()
C.enumerate()
D.range()
AnswerC

enumerate() provides both index and value directly.

Why this answer

enumerate() returns an iterator that yields pairs of (index, element) for each element in the iterable, making it ideal for accessing both.

115
MCQmedium

What is the result of the following expression? 3 + 4 * 2 ** 3 // 5

A.9
B.7
C.6
D.11
AnswerA

Correct order: 2**3=8, 4*8=32, 32//5=6, 3+6=9.

Why this answer

Option B is correct following operator precedence: ** first (2**3=8), then * (4*8=32), then // (32//5=6), then + (3+6=9). Options A, C, D reflect different precedence errors.

116
Multi-Selectmedium

Which THREE of the following code snippets will successfully print the string 'Hello, World!'? (Choose three.)

Select 3 answers
A.print('''Hello, World!''')
B.print("He said, "Hello!"")
C.print("Hello, World!")
D.print('It's a beautiful day')
E.print('Hello, World!')
AnswersA, C, E

Triple quotes are valid for strings.

Why this answer

Option A prints the string correctly. Option B uses single quotes, prints correctly. Option C is incorrect because the backslash-escaped double quotes inside the string cause a syntax error due to mismatched quotes.

Option D is correct: triple quotes allow multiline but it prints as is. Option E is incorrect: the string has unescaped double quotes inside double quotes, causing syntax error.

117
MCQmedium

What will be printed?

A.['255.255.255.0']
B.['192.168.1.10']
C.['192.168.1.10', '255.255.255.0', '192.168.1.1']
D.['192.168.1.10', '192.168.1.1']
AnswerC

All three IPs matched.

Why this answer

Option D is correct: findall returns all IP addresses in order: 192.168.1.10, 255.255.255.0, 192.168.1.1. Option A only finds first. Option B only finds subnet mask.

Option C finds two.

118
MCQeasy

Which of the following is a correct way to comment multiple lines in Python?

A.// comment
B./* comment */
C.""" comment """
D.# comment (each line)
AnswerC

Triple quotes create a multi-line string that can serve as a comment.

Why this answer

Triple quotes (''' or """) can be used as a multi-line string, which acts as a comment when not assigned to a variable. Although it is not a true comment, it is commonly used for multi-line comments in Python.

119
MCQmedium

A data scientist has a list: scores = [88, 92, 79, 93, 85]. They want to add 5 bonus points to each score and store the new scores. Which code accomplishes this?

A.scores = [s+5] for s in scores
B.scores = [s + 5 for s in scores]
C.for s in scores: s += 5
D.scores = scores + 5
AnswerB

Correct list comprehension.

Why this answer

Option D is correct because it uses list comprehension to add 5 to each element. Option A modifies the list in place with a loop but uses wrong syntax (no range). Option B tries to add 5 to the list, not elements.

Option C tries to assign to scores but uses wrong syntax.

120
MCQeasy

What is the output of the following code? print('Hello'.upper())

A.hello
B.HELLO!
C.HELLO
D.Hello
AnswerC

Converts to uppercase.

Why this answer

Option A is correct because the upper() method returns a string in uppercase. Option B is wrong because it returns the original case. Option C is wrong because the method changes the case.

Option D is wrong because upper() does not add an exclamation mark.

121
MCQeasy

Which of the following is a floating-point literal?

A.'3.14'
B.42
C.1+2j
D.3.14
AnswerD

Contains a decimal point, so float.

Why this answer

Option B is correct because '3.14' is a float literal. Option A is an integer. Option C is a complex number.

Option D is a string.

122
MCQeasy

A junior developer writes the following code to swap two variables: a = 5; b = 10; a = b; b = a. When they print a and b, what is the output?

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

After a = b, a becomes 10. Then b = a sets b to 10, so both are 10.

Why this answer

The code first assigns b's value (10) to a, so a becomes 10. Then b is assigned the value of a (which is now 10), so b becomes 10. Thus both a and b are 10.

123
MCQeasy

A developer wants to create a list of even numbers from 0 to 10 inclusive. Which code snippet will correctly produce [0, 2, 4, 6, 8, 10]?

A.list(range(0,11,2))
B.[x for x in range(11) if x%2==0]
C.[x*2 for x in range(6)]
D.All of the above
AnswerD

All three snippets produce the same list.

Why this answer

All three options produce the same list: Option A uses multiplication, option B filters, option C uses step. So all are correct.

124
MCQeasy

Which keyword is used to define a function in Python?

A.def
B.func
C.function
D.define
AnswerA

Standard keyword for function definition.

Why this answer

Option A is correct: 'def' defines a function. Option B 'function' is not a keyword. Option C 'define' is not a keyword.

Option D 'func' is not a keyword.

125
MCQmedium

A team is writing a Python script that reads a large log file and counts occurrences of ERROR. The script works but is very slow. They profile it and find that most time is spent reading the file line by line. Which optimization technique is most appropriate?

A.Use .readlines() to load the entire file into memory at once.
B.Examine the inner loop logic for unnecessary operations per line.
C.Open the file in binary mode to reduce overhead.
D.Rewrite the script using the 'with' statement for file handling.
AnswerB

Optimizing per-line operations rather than file reading is likely the key.

Why this answer

Option D is correct because reading the file line by line using a for loop is already efficient; the slowness might be due to other issues like excessive splitting or string operations. Option A is wrong because readlines() loads the entire file into memory, which could be worse. Option B is wrong if the script already reads efficiently.

Option C is wrong because 'rb' mode does not help with counting lines of text.

126
MCQhard

A developer writes: try: x = int('hello') except ValueError: x = 0 except TypeError: x = -1 finally: x = x + 1 What is the final value of x?

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

ValueError caught, then finally.

Why this answer

Option C is correct: int('hello') raises ValueError, so x=0, then finally adds 1 -> x=1. Option A ignores finally. Option B ignores exception handling.

Option D incorrectly assumes TypeError.

127
MCQhard

What is the output of the following code? try: print(1/0); except ZeroDivisionError: print('error'); finally: print('done')

A.error done
B.error
C.done error
D.1/0 done
AnswerA

Except prints 'error', then finally prints 'done'.

Why this answer

Option C is correct: division by zero raises ZeroDivisionError, caught by except, prints 'error', then finally block always runs, prints 'done'. Option A misses the error message. Option B misses finally.

Option D reverses order.

128
Drag & Dropmedium

Arrange the steps to slice a list in Python.

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

Steps
Order

Why this order

List slicing uses start:stop:step syntax within brackets.

129
MCQmedium

A Python function is designed to return the first element of a list. However, when passed an empty list, it raises an IndexError. Which best practice should be applied to handle this robustly?

A.Use try-except to catch IndexError and return None.
B.Check if len(lst) > 0 before accessing lst[0].
C.Always return None; let the caller handle IndexError.
D.Use a default parameter like lst=[0] to avoid empty list.
AnswerB

Clear and explicit guard condition.

Why this answer

Option B is correct because checking the length of the list before accessing an index is the most explicit and readable way to avoid an IndexError. This approach follows the principle of 'look before you leap' (LBYL), which is a common defensive programming pattern in Python. It clearly communicates the intent to handle empty lists without relying on exception handling for normal control flow.

Exam trap

Python Institute often tests the distinction between LBYL (look before you leap) and EAFP (easier to ask for forgiveness than permission) patterns, and the trap here is that candidates may incorrectly think catching an IndexError with try-except is the more 'Pythonic' approach, when in fact a simple conditional check is more appropriate for this predictable scenario.

How to eliminate wrong answers

Option A is wrong because using try-except to catch IndexError and return None is less efficient and less readable than a simple length check; exceptions should be reserved for truly exceptional conditions, not for routine control flow. Option C is wrong because always returning None without any check would still raise an IndexError when accessing lst[0] on an empty list, so it does not solve the problem. Option D is wrong because using a default parameter like lst=[0] is a dangerous mutable default argument that would be shared across all calls, and it does not prevent an IndexError when an empty list is explicitly passed.

130
MCQhard

A company has a Python script that imports a module from a package. The package structure is: mypackage/__init__.py, mypackage/module.py. The script uses 'from mypackage import module'. Which file must exist for this import to work?

A.mypackage.py
B.mypackage/__init__.py
C.module.py in the current directory
D.Only mypackage/module.py is needed
AnswerB

This file marks the directory as a Python package.

Why this answer

For a directory to be treated as a package, it must contain an __init__.py file (though optional in Python 3.3+ for namespace packages, it is required for regular packages).

131
MCQeasy

A Python program prompts the user for their age and stores it in a variable. Which is the correct way to convert the input to an integer?

A.age = str(input("Age: "))
B.age = float(input("Age: "))
C.age = input("Age: ")
D.age = int(input("Age: "))
AnswerD

Correct conversion.

Why this answer

The input() function returns a string, so you must convert it using int(). Option B is correct.

132
Multi-Selectmedium

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

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

Valid dict constructor.

Why this answer

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

133
Drag & Dropmedium

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

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

Steps
Order

Why this order

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

134
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

135
MCQmedium

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

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

Condition true.

Why this answer

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

Therefore, option D is correct.

Exam trap

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

How to eliminate wrong answers

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

136
Multi-Selectmedium

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

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

Leading underscore is allowed.

Why this answer

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

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

137
Multi-Selecteasy

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

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

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

Why this answer

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

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

138
MCQeasy

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

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

Correct and Pythonic.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

139
MCQhard

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

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

Limited to the function.

Why this answer

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

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

140
MCQmedium

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

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

The output explicitly states ZeroDivisionError on line 3.

Why this answer

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

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

141
MCQmedium

Refer to the exhibit. What is the output?

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

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

Why this answer

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

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

142
MCQhard

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

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

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

Why this answer

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

← PreviousPage 2 of 2 · 142 questions total

Ready to test yourself?

Try a timed practice session using only Python Fundamentals questions.