Level 1 — RecognitionPython Intermediate

Python Intermediate

20 minutes30 marksprintable — key stays hidden on paper

Chapter: 1.3 Python Intermediate Level: 1 — Recognition (MCQ, Matching, True/False with justification) Time Limit: 20 minutes Total Marks: 30


Section A — Multiple Choice (1 mark each, 12 marks)

Choose the single best answer.

Q1. Which statement correctly imports only the sqrt function from the math module?

  • (a) import sqrt from math
  • (b) from math import sqrt
  • (c) import math.sqrt
  • (d) from math import *sqrt

Q2. What does the file open mode 'a' do?

  • (a) Opens for reading only
  • (b) Truncates the file then writes
  • (c) Opens for appending, writing at the end of the file
  • (d) Opens a binary file for reading

Q3. Which method reads the entire file and returns a list of lines?

  • (a) read()
  • (b) readline()
  • (c) readlines()
  • (d) readtext()

Q4. In a decorator, functools.wraps is used to:

  • (a) Cache the function's return value
  • (b) Preserve the wrapped function's metadata (__name__, __doc__)
  • (c) Make the function run faster
  • (d) Convert a function into a generator

Q5. Which keyword turns an ordinary function into a generator function?

  • (a) return
  • (b) async
  • (c) yield
  • (d) gen

Q6. Which of these is the base class of most built-in exceptions you would normally catch?

  • (a) BaseException
  • (b) Exception
  • (c) Error
  • (d) RuntimeWarning

Q7. What does re.findall(r'\d+', 'a12b345') return?

  • (a) ['1', '2', '3', '4', '5']
  • (b) ['12', '345']
  • (c) '12345'
  • (d) [12, 345]

Q8. The with statement guarantees an object's cleanup by calling which method on exit?

  • (a) __exit__
  • (b) __close__
  • (c) __del__
  • (d) __leave__

Q9. Which collections type provides a dictionary that remembers insertion order and supports default values on missing keys (default factory)?

  • (a) OrderedDict
  • (b) defaultdict
  • (c) namedtuple
  • (d) Counter

Q10. Calling next() on an exhausted iterator raises:

  • (a) IndexError
  • (b) StopIteration
  • (c) ValueError
  • (d) KeyError

Q11. Which command creates a virtual environment named env?

  • (a) pip install env
  • (b) python -m venv env
  • (c) virtualenv --requirements env
  • (d) python venv env

Q12. The else block of a try statement executes when:

  • (a) An exception is raised
  • (b) No exception is raised in the try block
  • (c) Always, before finally
  • (d) Only if finally is absent

Section B — Matching (1 mark each, 8 marks)

Match each item in Column X to the correct description in Column Y. Write pairs like Q13→(iii).

Column X Column Y
Q13. import numpy as np (i) Counts hashable objects
Q14. itertools.count (ii) Immutable timestamp/date object
Q15. collections.Counter (iii) Aliasing an imported module
Q16. datetime.datetime (iv) Infinite arithmetic-step iterator
Q17. os module (v) Interpreter-related info (argv, exit)
Q18. sys module (vi) OS interaction (paths, environ)
Q19. re.sub (vii) Replaces pattern matches with a string
Q20. functools.reduce (viii) Folds an iterable to a single value

Section C — True / False with Justification (2 marks each, 10 marks)

State True or False (1 mark) and give a one-line justification (1 mark).

Q21. A custom exception class must inherit from Exception (directly or indirectly) to be raised with raise.

Q22. Opening a file with mode 'w' on an existing file preserves its previous contents.

Q23. A generator's send(value) resumes the generator, and value becomes the result of the paused yield expression.

Q24. The finally block runs even if a return occurs inside the try block.

Q25. In regex, the parentheses in r'(\d{4})-(\d{2})' create two capturing groups.

Answer keyMark scheme & solutions

Section A (1 mark each)

Q1. (b)from math import sqrt is the correct from…import syntax; other options are invalid grammar.

Q2. (c)'a' = append mode; writes go to end of file, file created if absent, existing content kept.

Q3. (c)readlines() returns a list of lines; read() returns one string, readline() returns one line.

Q4. (b)@functools.wraps copies metadata so the wrapper "looks like" the original function.

Q5. (c) — Presence of yield makes a function a generator.

Q6. (b)Exception is the standard base for catchable exceptions; BaseException also covers SystemExit/KeyboardInterrupt which we usually don't catch.

Q7. (b)\d+ matches one-or-more digits greedily → ['12', '345']; results are strings, not ints.

Q8. (a)with calls __enter__ on entry and __exit__ on exit.

Q9. (b)defaultdict supplies a default via factory on missing keys. (Ordinary dicts already keep insertion order in modern Python; the default factory is the distinguishing feature.)

Q10. (b) — Exhausted iterators raise StopIteration.

Q11. (b)python -m venv env creates the venv.

Q12. (b)else runs only when the try block completes without raising.


Section B (1 mark each)

  • Q13 → (iii) aliasing an imported module
  • Q14 → (iv) infinite arithmetic-step iterator
  • Q15 → (i) counts hashable objects
  • Q16 → (ii) immutable timestamp/date object
  • Q17 → (vi) OS interaction (paths, environ)
  • Q18 → (v) interpreter-related info (argv, exit)
  • Q19 → (vii) replaces pattern matches with a string
  • Q20 → (viii) folds an iterable to a single value

Section C (2 marks each: 1 verdict + 1 justification)

Q21. True.raise requires an object whose class derives from BaseException; custom exceptions conventionally subclass Exception. (Full inheritance from BaseException is technically the rule, but subclassing Exception is the standard/expected answer.)

Q22. False. — Mode 'w' truncates the file to zero length, destroying previous contents.

Q23. True.gen.send(value) resumes execution; the paused yield expression evaluates to value.

Q24. True.finally always executes, including when try/except contains a return (it runs before the actual return handoff).

Q25. True. — Each (...) is a capturing group; here there are two, capturing the 4-digit and 2-digit segments.


[
  {"claim":"re.findall(r'\\d+','a12b345') == ['12','345']","code":"import re; result = re.findall(r'\\d+','a12b345') == ['12','345']"},
  {"claim":"re pattern (\\d{4})-(\\d{2}) has 2 capturing groups","code":"import re; result = re.compile(r'(\\d{4})-(\\d{2})').groups == 2"},
  {"claim":"defaultdict supplies default via factory on missing key","code":"from collections import defaultdict; d = defaultdict(int); result = d['x'] == 0"},
  {"claim":"generator send delivers value into yield expression","code":"\ndef g():\n    x = yield 1\n    yield x*10\nit = g(); next(it); result = it.send(5) == 50"}
]