🌍 Python Programming · flashcards

Python Programming Modules, Packages and Error Handling Flashcards

51 question-and-answer cards covering Modules, Packages and Error Handling as it is examined in Python Programming. 24 of them are printed below, taken from across the deck — no signup, no paywall on the preview.

51Cards in deck
24Free preview
20Syllabus topics
~224Chars per answer
FreePrice

24 sample cards from the Modules, Packages and Error Handling deck

Sampled from the end of the deck, so these are different cards from the ones shown on the syllabus page.

  1. Distinguish `ValueError` from `TypeError`.

    `TypeError` is raised when an operation is applied to an object of an inappropriate type (e.g. `'a' + 1`). `ValueError` is raised when the type is right but the value is inappropriate (e.g. `int('abc')`).

  2. Which exception does dividing by zero raise, and what is its parent class?

    Dividing by zero raises `ZeroDivisionError`, which is a subclass of `ArithmeticError` (itself a subclass of `Exception`).

  3. What is the difference between `raise` with no arguments and `raise SomeError('msg')`?

    `raise SomeError('msg')` creates and raises a new exception with that message. A bare `raise` (only valid inside an `except` block) re-raises the exception currently being handled, preserving its original traceback.

  4. How do you raise an exception while explicitly chaining it to an original cause?

    Use `raise NewError('...') from original_exception`. This sets the new exception's `__cause__`, producing a traceback that reads 'The above exception was the direct cause of the following exception.'

  5. How do you define a custom exception class, and what should it inherit from?

    Define a class that inherits from `Exception` (or a more specific built-in exception), e.g. `class InsufficientFundsError(Exception): pass`. Inheriting from `Exception` makes it catchable by generic handlers and integrates it into the exception hierarchy.

  6. How would you create a base custom exception for a library and specific subclasses under it?

    Define one base, e.g. `class AppError(Exception): pass`, then subclass it: `class ConfigError(AppError): pass` and `class NetworkError(AppError): pass`. Clients can catch all library errors with `except AppError` or handle specific ones individually.

  7. What is the `assert` statement, which exception does it raise, and when is it disabled?

    `assert condition, message` raises `AssertionError` with the optional message if the condition is false. Assertions are removed when Python runs with the `-O` (optimize) flag, so they must not be used for essential runtime validation.

  8. What are the three arguments to the built-in `open()` that matter most, and what is the default mode?

    `open(file, mode, encoding)`. `file` is the path, `mode` controls read/write/append and text/binary, and `encoding` names the text codec (e.g. `'utf-8'`). The default mode is `'r'` (read, text).

  9. List the file mode characters `'r'`, `'w'`, `'a'`, `'x'`, `'b'`, `'t'`, `'+'` and what each means.

    `'r'` read; `'w'` write (truncate/create); `'a'` append (create if absent); `'x'` exclusive create (fail if exists); `'b'` binary; `'t'` text (default); `'+'` open for updating (read and write).

  10. Why must every opened file be closed, and what two ways guarantee closing?

    Closing flushes buffered writes to disk and releases the OS file handle. You can call `f.close()` explicitly (ideally in a `finally`), or better, use a `with` statement, which closes the file automatically even if an exception occurs.

  11. Contrast `read()`, `readline()`, and `readlines()` on a text file object.

    `read()` returns the entire remaining content as one string (or `read(n)` for n characters); `readline()` returns the next single line including its newline; `readlines()` returns a list of all lines. Iterating the file object directly (`for line in f`) reads it line by line, memory-efficiently.

  12. What is the difference between `write()` and `writelines()`, and does either add newlines?

    `write(s)` writes a single string and returns the number of characters written. `writelines(list)` writes each string in an iterable. Neither adds newline characters automatically — you must include `\n` yourself.

  13. What is a context manager, and what two special methods must an object implement to be one?

    A context manager is an object that defines runtime setup/teardown for a `with` block. It implements `__enter__(self)` (called on entry, its return value is bound by `as`) and `__exit__(self, exc_type, exc_val, exc_tb)` (called on exit for cleanup).

  14. Why is `with open(path) as f:` preferred over a manual open/close?

    The `with` statement uses the file's context-manager protocol to guarantee `f.close()` is called when the block exits — normally or via an exception — preventing resource leaks and eliminating the need for an explicit `try/finally`.

  15. How can you turn an ordinary generator function into a context manager without writing `__enter__`/`__exit__`?

    Decorate it with `@contextlib.contextmanager` and `yield` once. Code before the `yield` acts as `__enter__` (the yielded value is bound by `as`), and code after the `yield` acts as `__exit__`.

  16. When reading and writing binary files, what type is exchanged, and how does mode differ from text mode?

    Binary mode (`'rb'`, `'wb'`) exchanges `bytes` objects rather than `str`, performs no encoding/decoding or newline translation. Text mode (`'r'`, `'w'`) exchanges `str` and applies the given encoding plus universal-newline handling.

  17. Which module and functions serialize Python objects to binary and back, and what is a security caution?

    The `pickle` module: `pickle.dump(obj, file)` / `pickle.dumps(obj)` to serialize, and `pickle.load(file)` / `pickle.loads(data)` to deserialize. Caution: never unpickle data from an untrusted source, because it can execute arbitrary code.

  18. Give three common `os`/`os.path` operations for filesystem work.

    Examples: `os.getcwd()` (current directory), `os.listdir(path)` (list entries), `os.makedirs(path)` (create dirs), `os.remove(path)` (delete file), `os.rename(a, b)`; and `os.path.join`, `os.path.exists`, `os.path.basename`, `os.path.splitext` for path manipulation.

  19. What advantages does `pathlib.Path` offer over `os.path`, and how do you join paths with it?

    `pathlib` provides an object-oriented, cross-platform path API with methods like `.exists()`, `.is_file()`, `.read_text()`, `.glob()`, and `.parent`/`.name`/`.suffix` attributes. Paths are joined with the `/` operator: `Path('data') / 'file.txt'`.

  20. Name four useful functions from the `math` module and what they compute.

    `math.sqrt(x)` gives $\sqrt{x}$; `math.factorial(n)` gives $n!$; `math.floor(x)`/`math.ceil(x)` round down/up to integers; `math.log(x, base)` gives the logarithm. Constants include `math.pi` ($\pi$) and `math.e`.

  21. In the `random` module, distinguish `random.random()`, `random.randint(a, b)`, `random.uniform(a, b)`, and `random.choice(seq)`.

    `random.random()` returns a float in $[0, 1)$; `random.randint(a, b)` returns an integer in $[a, b]$ (both inclusive); `random.uniform(a, b)` returns a float in $[a, b]$; `random.choice(seq)` returns a random element from a non-empty sequence.

  22. How do you make results from the `random` module reproducible, and what is the difference between `random.shuffle` and `random.sample`?

    Call `random.seed(n)` to fix the pseudo-random sequence. `random.shuffle(lst)` reorders a list in place (returns `None`); `random.sample(pop, k)` returns a new list of `k` unique items without modifying the population.

  23. In the `datetime` module, distinguish `date`, `time`, `datetime`, and `timedelta`.

    `date` holds year/month/day; `time` holds hour/minute/second/microsecond; `datetime` combines both; `timedelta` represents a duration (difference between two dates or datetimes). Subtracting two `datetime` objects yields a `timedelta`.

  24. Which methods convert between `datetime` objects and strings, and what do their format codes `%Y`, `%m`, `%d`, `%H`, `%M`, `%S` mean?

    `dt.strftime(fmt)` formats a datetime to a string; `datetime.strptime(s, fmt)` parses a string to a datetime. Codes: `%Y` 4-digit year, `%m` month, `%d` day, `%H` 24-hour hour, `%M` minute, `%S` second.

What this deck covers

The Modules, Packages and Error Handling deck follows the Python Programming Modules, Packages and Error Handling syllabus — 5 chapters and 20 topics — so questions land on material that is genuinely examinable rather than trivia around it. That works out to roughly 10.2 cards per chapter.

Answers are written to be recallable, not just readable — averaging about 224 characters, which is long enough to carry the reasoning and short enough to say out loud.

A deck like this earns its keep on the second and third pass. Read the syllabus first so you know the shape of the subject, then use the cards to find the specific facts that have not stuck.

Modules, Packages and Error Handling flashcards FAQ

How many Modules, Packages and Error Handling flashcards are in this Python Programming deck?

51 cards. This page previews 24 of them, sampled evenly across the deck so you can judge the difficulty before installing anything.

Are these Python Programming flashcards free?

Yes. The preview here is free to read with no signup, and the full 51-card deck is free inside the Examius app.

What do the Modules, Packages and Error Handling cards cover?

They follow the Python Programming Modules, Packages and Error Handling syllabus — 5 chapters and 20 topics — so the questions track what is actually examinable.

How should I use these flashcards?

Read the syllabus first so you know the shape of the subject, then drill the deck. Examius schedules each card with spaced repetition, so cards you keep missing come back sooner and ones you know drift further apart.