Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 19

Python MCQ

3 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

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.

1

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

Code
print(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)
2

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 how open() works.

Example

Code
a = [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")
3

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.

Practice: pick the correct option

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.

Example

Code
import 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 work

Solved examples

Example 01 · Basic

Predict the output: print(3 * "ab" + "c" * 2)

Given Data:
    Required To Find:

    Printed text

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: 3 * "ab" gives "ababab"
    Step 2: "c" * 2 gives "cc"
    Step 3: Concatenate: "abababcc"
    Final Answer: abababcc

    Approach note: Repetition binds tighter than +.

    Example 02 · Intermediate

    Predict the output: x = [1, 2, 3]; y = x; y += [4]; z = x + [5]; print(x, z)

    Given Data:
      Required To Find:

      Printed lists

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: y += [4] extends the list in place, so x is also [1, 2, 3, 4]
      Step 2: z = x + [5] creates a new list [1, 2, 3, 4, 5]
      Final Answer: [1, 2, 3, 4] [1, 2, 3, 4, 5]

      Approach note: += on a list mutates; + builds a new list.

      Example 03 · Intermediate

      Predict the output: def f(a, b=[]): b.append(a); return len(b) print(f(1), f(2), f(3))

      Given Data:
        Required To Find:

        Printed numbers

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: b is created once and reused
        Step 2: Calls append 1, 2, 3 to the same list: lengths 1, 2, 3
        Final Answer: 1 2 3

        Approach note: Fix by using None as the default.

        Example 04 · Basic

        What is the output of: print(list(map(lambda x: x*x, [1, 2, 3])))?

        Given Data:
          Required To Find:

          Result list

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: lambda squares each element
          Step 2: map applies it lazily
          Step 3: list(...) materialises [1, 4, 9]
          Final Answer: [1, 4, 9]

          Approach note: map returns an iterator; wrap with list() to see values.

          Real-world applications

          Python

          Using Python MCQs in real projects

          Campus placement tests, Python certification exams, quick revision before interviews.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          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

          1. / returns float, // floors, ** is right-associative.
          2. and/or return operands; non-empty strings are truthy.
          3. List assignment aliases; use copy/deepcopy to duplicate.
          4. Mutable default arguments are shared; use None.
          5. is = identity, == = equality.
          6. File modes: r, w, a, x; with closes automatically.
          7. MRO is child then parents left to right.
          8. Lambdas in loops capture the variable, not the value.

          Practice questions

          Question 1 · MCQ (Interview / semester)

          What is the type of 5 / 2 in Python 3?

          Question 2 · MCQ (Interview / semester)

          print(7 // 2, 7 % 2) outputs

          Question 3 · MCQ (Interview / semester)

          The value of 2 ** 3 ** 2 is

          Question 4 · MCQ (Interview / semester)

          Which is a valid variable name?

          Question 5 · MCQ (Interview / semester)

          print("Py" * 3) prints

          Question 6 · MCQ (Interview / semester)

          bool("False") evaluates to

          Question 7 · MCQ (Interview / semester)

          print(not 0, 5 and 0, 0 or 7) prints

          Question 8 · MCQ (Interview / semester)

          round(2.5) returns

          Question 9 · MCQ (Interview / semester)

          a = [1, 2, 3]; b = a; b.append(4); print(a) gives

          Question 10 · MCQ (Interview / semester)

          [1, 2, 3, 4, 5][1:4] equals

          Question 11 · MCQ (Interview / semester)

          len([1, [2, 3], 4]) is

          Question 12 · MCQ (Interview / semester)

          m = [[0] * 2] * 2; m[0][0] = 1; print(m) gives

          Question 13 · MCQ (Interview / semester)

          sorted([3, 1, 2], reverse=True) returns

          Question 14 · MCQ (Interview / semester)

          class A: x = 1; a = A(); a.x = 5; print(A.x) gives

          Question 15 · MCQ (Interview / semester)

          Which call runs the parent constructor?

          Question 16 · MCQ (Interview / semester)

          For class D(B, C) where B and C both inherit A, the MRO is

          Question 17 · MCQ (Interview / semester)

          The first parameter of a @classmethod is conventionally

          Question 18 · MCQ (Interview / semester)

          Inside class Account, self.__x is stored as

          Question 19 · MCQ (Interview / semester)

          Instantiating a class with an unimplemented @abstractmethod raises

          Question 20 · MCQ (Interview / semester)

          The default mode of open("f.txt") is

          Question 21 · MCQ (Interview / semester)

          Which file mode raises an error if the file already exists?

          Question 22 · MCQ (Interview / semester)

          f.read() and f.readlines() return respectively

          Question 23 · MCQ (Interview / semester)

          If text is {"a": 1}, type(json.loads(text)["a"]) is

          Question 24 · MCQ (Interview / semester)

          Main advantage of with open(...) as f is

          Question 25 · MCQ (Interview / semester)

          print(add_item(1), add_item(2)) for def add_item(x, b=[]): b.append(x); return b prints

          Question 26 · MCQ (Interview / semester)

          print([1, 2] == [1, 2], [1, 2] is [1, 2]) prints

          Question 27 · MCQ (Interview / semester)

          0.1 + 0.2 == 0.3 evaluates to

          Question 28 · MCQ (Interview / semester)

          funcs = [lambda: i for i in range(3)]; [f() for f in funcs] gives

          Question 29 · MCQ (Interview / semester)

          The GIL in CPython means

          Question 30 · MCQ (Interview / semester)

          Which is true about tuples vs lists?

          Question 31 · MCQ (Interview / semester)

          Which block of try/except/else/finally always runs?

          Question 32 · MCQ (Interview / semester)

          Which can be a dictionary key?