🌍 CS50x: Introduction to Computer Science · flashcards
CS50x: Introduction to Computer Science Python Flashcards
50 question-and-answer cards covering Python as it is examined in CS50x: Introduction to Computer Science. 24 of them are printed below, taken from across the deck — no signup, no paywall on the preview.
24 sample cards from the Python deck
Sampled from the end of the deck, so these are different cards from the ones shown on the syllabus page.
What is a Python dictionary, and what is its key syntax for creation and lookup?
A dict is a mutable collection of key–value pairs with unique keys: created as `d = {"name": "Ali", "age": 20}`, values are accessed by key with `d["name"]` or safely with `d.get("name")`.
What two defining properties does a Python set have, and what syntax creates one?
A set stores only unique elements (duplicates are discarded) and is unordered; create one with `{1, 2, 3}` or `set(iterable)` — e.g., `set([1, 1, 2])` gives `{1, 2}`. An empty set requires `set()`, since `{}` is an empty dict.
In Python list indexing, what do `lst[0]`, `lst[-1]`, and the slice `lst[1:3]` return?
`lst[0]` is the first element, `lst[-1]` is the last element (negative indices count from the end), and `lst[1:3]` is a new list of the elements at indices 1 and 2 (the end index is exclusive).
Name the list methods to add one element to the end, insert at a position, remove by value, and sort in place.
`append(x)` adds to the end; `insert(i, x)` inserts at index i; `remove(x)` deletes the first occurrence of x; `sort()` orders the list in place (while the built-in `sorted(lst)` returns a new sorted list).
How do you iterate over both keys and values of a Python dictionary in one loop?
Use the `items()` method: `for key, value in d.items():` — whereas `for key in d:` iterates over keys only, and `d.values()` gives values only.
What is the recommended way to open a file in Python, and why?
Use a context manager: `with open("file.txt") as f:` — the `with` statement automatically closes the file when the block ends, even if an exception occurs, avoiding leaked file handles.
What do the file modes "r", "w", and "a" mean in Python's `open()`?
"r" opens for reading (default; error if the file does not exist), "w" opens for writing and truncates/overwrites existing content, "a" opens for appending, adding new content to the end of the file.
Contrast the file-reading calls `read()`, `readline()`, and `readlines()` in Python.
`read()` returns the entire file as one string; `readline()` returns the next single line; `readlines()` returns a list of all lines (each usually ending with "\n", often cleaned with `strip()` or `rstrip()`).
Which standard library module reads and writes CSV files in Python, and what are its key classes for working with column names?
The `csv` module: `csv.DictReader(f)` reads each row as a dictionary keyed by the header names, and `csv.DictWriter(f, fieldnames=...)` writes rows from dictionaries, making code robust to column order.
What is an exception in Python, and how does it differ from a syntax error?
An exception is a runtime error raised while the program executes (e.g., `ValueError`, `ZeroDivisionError`) and can be caught and handled; a syntax error is detected before execution when the code cannot be parsed and cannot be caught by the running program.
Write the general structure of Python exception handling with `try`, `except`, and `else`.
Put risky code in `try:`; handle a specific failure in `except SomeError:`; the optional `else:` block runs only if no exception was raised. Example: `try: n = int(x)` / `except ValueError: ...` / `else: use n`.
Which exceptions are raised by `int("cat")` and by `1 / 0` in Python?
`int("cat")` raises `ValueError` (right type, inappropriate value); `1 / 0` raises `ZeroDivisionError`.
What do the `raise` statement and the `finally` clause do in Python exception handling?
`raise SomeError("message")` deliberately triggers an exception; a `finally:` block always executes after the try/except, whether or not an exception occurred, and is used for cleanup.
Which Python module provides regular expressions, and what is the difference between `re.search` and `re.fullmatch`?
The `re` module. `re.search(pattern, s)` finds the pattern anywhere in the string; `re.fullmatch(pattern, s)` requires the entire string to match the pattern. Both return a match object or `None`.
In Python regular expressions, what do the metacharacters `.`, `*`, `+`, and `?` mean?
`.` matches any single character (except newline); `*` means 0 or more of the preceding element; `+` means 1 or more; `?` means 0 or 1 (optional). Braces give exact counts, e.g., `a{2,4}` matches 2 to 4 a's.
In Python regex, what do `^`, `$`, `\d`, `\w`, and `\s` match?
`^` anchors the match at the start of the string and `$` at the end; `\d` matches a digit, `\w` matches a word character (letter, digit, or underscore), `\s` matches whitespace. Capitalized forms (`\D`, `\W`, `\S`) match the opposite.
What are capture groups in Python regular expressions, and how do you retrieve captured text?
Parentheses in a pattern, e.g., `(\w+), (\w+)`, capture the matched substrings; on a match object you retrieve them with `m.group(1)`, `m.group(2)` (or `m.groups()`), where `group(0)` is the whole match.
In Python OOP, what is the difference between a class and an object (instance)?
A class is a blueprint/template defining attributes and methods (e.g., `class Student:`); an object is a concrete instance created from the class (e.g., `s = Student()`), each with its own attribute values.
What is the role of `__init__` and the `self` parameter in a Python class?
`__init__` is the constructor, called automatically when an instance is created, and typically sets instance attributes (e.g., `self.name = name`); `self` refers to the specific instance and is the first parameter of every instance method.
What does the `__str__` method do in a Python class?
It returns the human-readable string representation of the object, used automatically by `print(obj)` and `str(obj)` — e.g., returning `f"{self.name}, {self.house}"`.
What do the `@property` decorator and inheritance provide in Python OOP?
`@property` defines a getter (with a matching `@name.setter` for validation) so an attribute is accessed like a variable but computed/validated through methods; inheritance (`class Wizard(Student):`) lets a subclass reuse and extend a parent class's attributes and methods, calling `super().__init__()` to initialize the parent part.
Which Python values are falsy in a Boolean context?
`False`, `None`, numeric zeros (0, 0.0), and empty containers: "" (empty string), `[]`, `()`, `{}`, and `set()`. Everything else is truthy, so `if items:` tests whether a collection is non-empty.
What is a list comprehension in Python? Give the pattern that squares every number in a list.
A one-line expression that builds a new list from an iterable: `[expression for item in iterable]`. Squaring: `squares = [x ** 2 for x in numbers]` computes $x^{2}$ for each element.
How do you add a filtering condition to a Python comprehension, and what other comprehension types exist besides lists?
Append an `if` clause: `[x for x in nums if x % 2 == 0]` keeps only even numbers. Python also has dict comprehensions `{k: v for ...}`, set comprehensions `{x for ...}`, and generator expressions `(x for ...)`.
What this deck covers
The Python deck follows the CS50x: Introduction to Computer Science Python syllabus — 4 chapters and 13 topics — so questions land on material that is genuinely examinable rather than trivia around it. That works out to roughly 12.5 cards per chapter.
Answers are written to be recallable, not just readable — averaging about 203 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.
Python flashcards FAQ
How many Python flashcards are in this CS50x: Introduction to Computer Science deck?
50 cards. This page previews 24 of them, sampled evenly across the deck so you can judge the difficulty before installing anything.
Are these CS50x: Introduction to Computer Science flashcards free?
Yes. The preview here is free to read with no signup, and the full 50-card deck is free inside the Examius app.
What do the Python cards cover?
They follow the CS50x: Introduction to Computer Science Python syllabus — 4 chapters and 13 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.