Chapter 19
Python MCQ
3 topics · 1 sections · beginner-friendly study notes · Updated
Multiple-choice practice for Python: core syntax and operators, lists and data structures, object-oriented programming, file handling and common interview traps.
Each question has a one-line explanation so you learn from mistakes.
MCQs reveal gaps quickly and are used in placements, certifications and online assessments.
Campus placement tests, Python certification exams, quick revision before interviews.
Python MCQ Basics
This set covers fundamental syntax: arithmetic operators, operator precedence, boolean logic, strings and slicing, type conversion and variable naming rules.
In short: Warm-up questions: what does this one-liner print?
Think about it
Basic questions are quick marks; mistakes here are costly. Typical first section of placement tests.
Key facts: / always returns float, // is floor division, ** is right-associative, and/or return one of their operands (not necessarily True/False), non-empty strings are truthy (even "False"), round() uses banker rounding (round half to even), and slicing s[start:stop:step] never raises IndexError.
Variable names cannot start with a digit or be keywords and are case-sensitive.
Strategy: evaluate step by step, write down the types, and remember that Python is indentation-sensitive.
Key points
- Floor division: // rounds toward negative infinity.
- Short-circuit: and/or stop evaluating as soon as the result is known.
- Truthiness: Empty or zero values are falsy; all others are truthy.
Example
Codeprint(type(5 / 2)) # <class 'float'>
print(7 // 2, 7 % 2, -7 // 2) # 3 1 -4
print(2 ** 3 ** 2) # 512 (right-associative: 2 ** 9)
print("Py" * 3) # PyPyPy
print(bool("False"), bool("")) # True False
print(not 0, 5 and 0, 0 or 7) # True 0 7
print(round(2.5), round(3.5)) # 2 4 (banker's rounding)
print(int("12") + 3) # 15
print("abc"[1:], "abc"[::-1], "abc"[10:]) # bc cba (empty string)
print(10 / 3 == 3.3333333333333335) # True
x = y = 5
x += 1
print(x, y) # 6 5 (ints are immutable)Python MCQ Part 2
This set tests lists, tuples, dictionaries, comprehensions, classes, inheritance, name mangling, file modes, with-statements and JSON.
In short: Intermediate questions on data structures, classes and files.
Think about it
These areas are where most output-prediction questions come from. Second section of most coding assessments.
Key facts: assignment of a list copies the reference, not the list; [[0] * 2] * 2 repeats the same inner list; append adds one item while extend adds each element; sorted() returns a new list and list.
sort() returns None; tuples are immutable but can hold mutable objects; class attributes are shared and assigning through an instance creates an instance attribute; super().
__init__() calls the next class in the MRO; open() defaults to mode "r", "w" truncates, "a" appends and "x" fails if the file exists; with closes files automatically; JSON arrays become lists and objects become dicts.
Key points
- Aliasing: Two names referring to the same object.
- MRO: Method resolution order for inheritance.
- File mode:
Letter(s)that define howopen()works.
Read more
Example
Codea = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4] (same list)
m = [[0] * 2] * 2
m[0][0] = 1
print(m) # [[1, 0], [1, 0]]
print([x * 2 for x in range(3)]) # [0, 2, 4]
print(sorted([3, 1, 2], reverse=True), [3, 1, 2].sort()) # [3, 2, 1] None
class A:
x = 1
a = A()
a.x = 5
print(A.x, a.x) # 1 5
class B(A): pass
class C(A): pass
class D(B, C): pass
print([k.__name__ for k in D.__mro__]) # ['D', 'B', 'C', 'A', 'object']
import json, os
with open("t.txt", "w") as f:
f.write("hi")
with open("t.txt") as f: # default mode is "r"
print(f.read(), type(json.loads('{"a": 1}')["a"])) # hi <class 'int'>
os.remove("t.txt")Python Interview MCQs
This set covers classic interview traps: mutable default arguments, is versus ==, shallow versus deep copy, floating-point equality, late-binding closures, list versus tuple, hashability and the GIL.
In short: Questions interviewers love because the obvious answer is often wrong.
Think about it
Employers use these to separate memorised syntax from real understanding. Phone-screen and technical-round questions at product companies.
Mutable default arguments are evaluated once at function definition, so the same list is reused; use None as the default.
== compares values, is compares identity (never use is for numbers or strings, except with None).
copy.
copy duplicates only the outer container, deepcopy duplicates nested objects.
Floats cannot represent 0.1 exactly so use math.
isclose or Decimal.
Closures capture variables, not values, so lambdas created in a loop all see the final loop value; bind with a default argument i=i.
Dictionary keys and set members must be hashable (immutable): lists are not, tuples of hashables are.
In CPython the Global Interpreter Lock allows only one thread to execute Python bytecode at a time, so CPU-bound parallelism needs multiprocessing, while threads still help I/O-bound work.
Key points
- Hashable: Immutable object with a stable hash; usable as dict key.
- GIL: CPython lock that lets one thread run Python bytecode at a time.
- Late binding: Closure variables are looked up when the function runs.
- Deep copy: Recursive copy of nested objects.
Read more
Example
Codeimport copy, math
def add_item(x, bucket=[]): # mutable default: created once
bucket.append(x)
return bucket
print(add_item(1), add_item(2)) # [1, 2] [1, 2] (same list)
def add_item_fixed(x, bucket=None):
bucket = [] if bucket is None else bucket
bucket.append(x)
return bucket
print(add_item_fixed(1), add_item_fixed(2)) # [1] [2]
print([1, 2] == [1, 2], [1, 2] is [1, 2]) # True False
print(0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3)) # False True
nested = [[1], [2]]
shallow, deep = copy.copy(nested), copy.deepcopy(nested)
nested[0].append(9)
print(shallow[0], deep[0]) # [1, 9] [1]
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]
try:
{[1, 2]: "x"}
except TypeError as e:
print("TypeError:", e) # unhashable type: 'list'
print({(1, 2): "ok"}) # tuple keys workSolved examples
Predict the output: print(3 * "ab" + "c" * 2)
Printed text
Formula Applied:—Approach note: Repetition binds tighter than +.
Predict the output: x = [1, 2, 3]; y = x; y += [4]; z = x + [5]; print(x, z)
Printed lists
Formula Applied:—Approach note: += on a list mutates; + builds a new list.
Predict the output: def f(a, b=[]): b.append(a); return len(b) print(f(1), f(2), f(3))
Printed numbers
Formula Applied:—Approach note: Fix by using None as the default.
What is the output of: print(list(map(lambda x: x*x, [1, 2, 3])))?
Result list
Formula Applied:—Approach note: map returns an iterator; wrap with list() to see values.
Real-world applications
Using Python MCQs in real projects
Campus placement tests, Python certification exams, quick revision before interviews.
Common mistakes
❌ Myth: and/or always return True or False.
Why this is wrong: They return one of the operands.
✅ Verified Truth: 5 and 0 is 0; 0 or 7 is 7.
⚠️ Exam Tip: Remember the short-circuit rule.
❌ Myth: b = a copies a list.
Why this is wrong: It only copies the reference.
✅ Verified Truth: Use a.copy(), a[:] or copy.deepcopy.
⚠️ Exam Tip: Aliasing questions are very common.
❌ Myth: is and == are interchangeable.
Why this is wrong: is checks identity, == checks equality.
✅ Verified Truth: Use == for values and is only for None.
⚠️ Exam Tip: Small-int caching makes is seem to work, misleadingly.
Revision notes
Multiple-choice practice for Python: core syntax and operators, lists and data structures, object-oriented programming, file handling and common interview traps. Each question has a one-line explanation so you learn from mistakes.
High-Yield Quick Revision Points
- / returns float, // floors, ** is right-associative.
- and/or return operands; non-empty strings are truthy.
- List assignment aliases; use copy/deepcopy to duplicate.
- Mutable default arguments are shared; use None.
- is = identity, == = equality.
- File modes: r, w, a, x; with closes automatically.
- MRO is child then parents left to right.
- Lambdas in loops capture the variable, not the value.
Practice questions
What is the type of 5 / 2 in Python 3?
print(7 // 2, 7 % 2) outputs
The value of 2 ** 3 ** 2 is
Which is a valid variable name?
print("Py" * 3) prints
bool("False") evaluates to
print(not 0, 5 and 0, 0 or 7) prints
round(2.5) returns
a = [1, 2, 3]; b = a; b.append(4); print(a) gives
[1, 2, 3, 4, 5][1:4] equals
len([1, [2, 3], 4]) is
m = [[0] * 2] * 2; m[0][0] = 1; print(m) gives
sorted([3, 1, 2], reverse=True) returns
class A: x = 1; a = A(); a.x = 5; print(A.x) gives
Which call runs the parent constructor?
For class D(B, C) where B and C both inherit A, the MRO is
The first parameter of a @classmethod is conventionally
Inside class Account, self.__x is stored as
Instantiating a class with an unimplemented @abstractmethod raises
The default mode of open("f.txt") is
Which file mode raises an error if the file already exists?
f.read() and f.readlines() return respectively
If text is {"a": 1}, type(json.loads(text)["a"]) is
Main advantage of with open(...) as f is
print(add_item(1), add_item(2)) for def add_item(x, b=[]): b.append(x); return b prints
print([1, 2] == [1, 2], [1, 2] is [1, 2]) prints
0.1 + 0.2 == 0.3 evaluates to
funcs = [lambda: i for i in range(3)]; [f() for f in funcs] gives
The GIL in CPython means
Which is true about tuples vs lists?
Which block of try/except/else/finally always runs?
Which can be a dictionary key?