Python MCQs - Modules, Files, Iterators, Generators and Decorators (Set 6)

Python MCQs - Modules, Files, Iterators, Generators and Decorators (Set 6) - CodingHumans

This final set moves to the features that make Python code modular and memory-efficient. It covers imports and the __name__ check, module caching, file modes and reading methods, the with statement, the iterator protocol, generator functions with yield, send and yield from, itertools, and decorators including stacked and parameterised ones. These topics feature in advanced Python interview rounds, placement assessments and university practical exams, and the snippets below help you trace their behaviour precisely.

How to practise: read each question and tap the option you think is correct. You will see right away whether you got it, along with a short explanation, and your score is tracked at the bottom of the screen. This set has 18 questions.

Python MCQ series: Set 1 | Set 2 | Set 3 | Set 4 | Set 5 | Set 6

Topics covered in this set

  • Imports, __name__ and module caching
  • File modes and reading methods
  • The with statement and context managers
  • Iterator protocol: __iter__ and __next__
  • Generators: yield, send and yield from
  • itertools basics
  • Decorators, functools.wraps and parameterised decorators

Python MCQs with answers and explanations

Q1. What is the output of the following code?

def gen():
    yield 1
    yield 2
    return 3

print(list(gen()))

a) [1, 2, 3]

b) [3]

c) [1, 2]

d) SyntaxError

Q2. What is the output of the following code?

g = (i for i in range(1))
next(g)
next(g)

a) None

b) StopIteration

c) IndexError

d) 0

Q3. What is the output of the following code?

def g():
    x = yield 1
    yield x * 2

it = g()
a = next(it)
b = it.send(5)
print(a, b)

a) 1 2

b) 1 10

c) 5 10

d) TypeError

Q4. What is the output of the following code?

def inner():
    yield 1
    yield 2

def outer():
    yield 0
    yield from inner()
    yield 3

print(list(outer()))

a) [0, 1, 2]

b) [0, 3]

c) [0, [1, 2], 3]

d) [0, 1, 2, 3]

Q5. What is the output of the following code?

def double(f):
    def w(*a):
        return f(*a) * 2
    return w

@double
def sq(x):
    return x * x

print(sq(3))

a) 9

b) 36

c) 18

d) 12

Q6. What is the output of the following code?

def a(f): return lambda: "a(" + f() + ")"
def b(f): return lambda: "b(" + f() + ")"

@a
@b
def h():
    return "h"

print(h())

a) a(b(h))

b) b(a(h))

c) a(h)b(h)

d) h

Q7. What is the output of the following code?

def deco(f):
    def wrapper():
        return f()
    return wrapper

@deco
def hello():
    pass

print(hello.__name__)

a) hello

b) deco

c) wrapper

d) None

Q8. What is the output of the following code?

class Count:
    def __init__(self, n): self.n = n
    def __iter__(self): return self
    def __next__(self):
        if self.n <= 0:
            raise StopIteration
        self.n -= 1
        return self.n

c = Count(3)
print(list(c), list(c))

a) [2, 1, 0] [2, 1, 0]

b) [3, 2, 1] []

c) [2, 1, 0] []

d) [3, 2, 1] [3, 2, 1]

Q9. Which file mode opens a file for writing but raises FileExistsError if the file already exists?

a) "w"

b) "x"

c) "a"

d) "r+"

Q10. What is the output of the following code?

with open("demo.txt", "w") as f:
    f.write("ab\ncd\n")

with open("demo.txt") as f:
    print(f.readlines())

a) ['ab', 'cd']

b) ['ab\ncd\n']

c) ['ab\n', 'cd\n', '']

d) ['ab\n', 'cd\n']

Q11. What is the output of the following code?

with open("t.txt", "w") as f:
    f.write("xyz")

with open("t.txt") as f:
    f.read(2)
    print(repr(f.read()), repr(f.read()))

a) 'xyz' ''

b) 'z' 'z'

c) 'z' None

d) 'z' ''

Q12. A file utils.py ends with the block if __name__ == "__main__": main(). When is main() called?

a) Every time utils.py is imported

b) Only when utils.py is run directly as a script

c) Only when utils.py is imported by another module

d) Never, because __name__ is always "utils"

Q13. If a module defines no __all__, which names does from module import * skip?

a) Names that begin with an underscore

b) Names of functions

c) Names of classes

d) Names defined after the first function

Q14. What is the output of the following code?

import itertools
print(list(itertools.islice(itertools.count(5, 3), 4)))

a) [5, 8, 11, 14]

b) [5, 8, 11]

c) [5, 6, 7, 8]

d) [3, 6, 9, 12]

Q15. What is the output of the following code?

it = iter([1, 2, 3, 4, 5])
print(list(zip(it, it)))

a) [(1, 2), (3, 4)]

b) [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]

c) [(1, 2), (3, 4), (5,)]

d) [(1, 2), (3, 4), (5, None)]

Q16. What is the output of the following code?

nums = [1, 2, 3]
print(next(nums))

a) 1

b) TypeError

c) StopIteration

d) [1, 2, 3]

Q17. What is the output of the following code?

def repeat(n):
    def deco(f):
        def w():
            return [f() for _ in range(n)]
        return w
    return deco

@repeat(3)
def one():
    return 1

print(one())

a) [1, 1, 1]

b) 1

c) 3

d) TypeError

Q18. A program executes import config twice, in two different functions. How many times does the top-level code of config.py run?

a) Twice

b) Zero times until a function from it is called

c) Once per function that imports it, plus once at start-up

d) Once

Quick revision notes

  • A module's top-level code runs only on its first import; later imports reuse sys.modules.
  • __name__ is "__main__" when a file is run directly and the module name when imported.
  • File modes: r read, w truncate/create, a append, x exclusive create, b binary, + read and write.
  • with open(...) closes the file automatically, even if an exception occurs.
  • An iterator implements __iter__ (returning itself) and __next__ (raising StopIteration at the end).
  • Lists are iterable but not iterators; call iter() to get an iterator.
  • A generator's return value is carried in StopIteration and is not yielded.
  • @a on top of @b means f = a(b(f)); use functools.wraps to keep the original name and docstring.

Frequently asked questions

What is the difference between an iterable and an iterator in Python?

An iterable is any object that can return an iterator via iter(), such as a list or string. An iterator is the object that actually produces values one by one with next() and remembers its position, and it is exhausted after one pass.

What is the difference between yield and return?

return ends a function and sends back one value. yield pauses a generator function, hands a value to the caller and resumes from the same point on the next request, so a sequence can be produced lazily.

Why should functools.wraps be used in decorators?

A decorator replaces the original function with a wrapper, which otherwise has its own name and docstring. functools.wraps copies the metadata such as __name__, __doc__ and __wrapped__ to the wrapper, which helps debugging, documentation and introspection.

Comments

Answered 0/0Correct 0