🌍 CS50x: Introduction to Computer Science · subject

CS50x: Introduction to Computer Science Python Syllabus

The Python syllabus for CS50x: Introduction to Computer Science in full: 4 chapters and 13 topics, every one listed below, plus 50 Python flashcards with answers.

4Chapters
13Topics
50Flashcards

Python syllabus: all 4 chapters

Expand any chapter to see its topics and sub-topics.

  1. Python Fundamentals

    4 topics
    • Functions, Arguments, and Return Values
    • Variables and Data Types
    • Conditionals and Boolean Expressions
    • Loops
  2. Modules and Libraries

    3 topics
    • Modules and Packages
    • The Standard Library
    • Third-Party Libraries with pip
  3. Data and I/O

    3 topics
    • Lists, Tuples, Dictionaries, and Sets
    • File I/O
    • Exceptions
  4. Advanced Python

    3 topics
    • Regular Expressions
    • Object-Oriented Programming
    • Truthiness and Comprehensions

CS50x: Introduction to Computer Science Python flashcards — 50 questions with answers

  1. In Python, what keyword defines a function, and what is the basic syntax?

    The `def` keyword defines a function: `def name(parameters):` followed by an indented block. Example: `def square(x): return x * x`.

  2. What is the difference between a parameter and an argument in Python?

    A parameter is the variable named in the function definition (e.g., `x` in `def f(x):`); an argument is the actual value passed when the function is called (e.g., `f(5)` passes the argument 5).

  3. What does a Python function return if it has no `return` statement (or a bare `return`)?

    It returns `None`, Python's special object representing the absence of a value.

  4. What is the difference between positional arguments, keyword arguments, and default parameter values in Python?

    Positional arguments are matched to parameters by order; keyword arguments are matched by name (e.g., `f(x=3)`); default values in the definition (e.g., `def f(x, n=2):`) make a parameter optional.

  5. Name the four primitive built-in data types in Python for numbers, text, and truth values, with an example of each.

    `int` (whole numbers, e.g., 42), `float` (decimals, e.g., 3.14), `str` (text, e.g., "hello"), and `bool` (`True` or `False`).

  6. Is Python statically or dynamically typed, and what does that mean for variables?

    Dynamically typed: a variable's type is determined by the value currently assigned at runtime, no type declaration is needed, and the same name can later be bound to a value of a different type.

  7. In Python, what do the operators `/`, `//`, `%`, and `**` compute?

    `/` is true division (always returns a float), `//` is floor division (e.g., 7 // 2 = 3, i.e., $\lfloor \frac{7}{2} \rfloor$), `%` is the modulo/remainder (7 % 2 = 1), and `**` is exponentiation (e.g., 2 ** 3 computes $2^{3} = 8$).

  8. How do you convert a string to an integer in Python, and why is this needed for user input?

    Use `int(s)`, e.g., `n = int(input("Number: "))`. It is needed because `input()` always returns a string, so arithmetic requires explicit conversion (casting) with `int()` or `float()`.

  9. What is the difference between `=` and `==` in Python?

    `=` is the assignment operator (binds a value to a variable); `==` is the equality comparison operator (evaluates to `True` or `False`).

  10. Write the general structure of an if/elif/else block in Python and state how many branches execute.

    `if condition:` ... `elif other_condition:` ... `else:` ... — exactly one branch executes: the first condition that is true, or the `else` block if none are.

  11. What are Python's three logical (Boolean) operators, and how do they differ from other languages' symbols?

    `and`, `or`, and `not` — Python uses English words instead of `&&`, `||`, and `!`.

  12. What does short-circuit evaluation mean for `and` and `or` in Python?

    `x and y` stops and returns `x` if `x` is falsy (y is never evaluated); `x or y` stops and returns `x` if `x` is truthy. Evaluation halts as soon as the result is determined.

  13. What is the difference between a `while` loop and a `for` loop in Python?

    A `while` loop repeats as long as a condition remains true (unknown number of iterations); a `for` loop iterates over each item of an iterable (e.g., `for x in range(5):`), typically for a known sequence of items.

  14. What sequence does `range(n)` produce, and what do `range(a, b)` and `range(a, b, s)` produce?

    `range(n)` yields 0, 1, ..., n-1. `range(a, b)` yields a up to b-1 (end exclusive). `range(a, b, s)` yields a, a+s, a+2s, ... while still less than b (step s).

  15. What do `break` and `continue` do inside a Python loop?

    `break` exits the loop entirely and immediately; `continue` skips the rest of the current iteration and jumps to the next iteration.

  16. How do you write an intentional infinite loop in Python, and how is it typically exited?

    `while True:` creates an infinite loop; it is exited with `break` when some condition is met (a common pattern for validating user input).

  17. What is the difference between a module and a package in Python?

    A module is a single `.py` file containing Python definitions; a package is a directory of modules (traditionally containing an `__init__.py` file) that groups related modules under one namespace.

  18. Contrast `import module` with `from module import name` in Python.

    `import csv` binds the module object, so you access members as `csv.reader`; `from csv import reader` imports the name directly into the current namespace, so you call `reader` without the module prefix.

  19. What does the idiom `if __name__ == "__main__":` do in a Python file?

    It runs the guarded code only when the file is executed directly as a script; when the file is imported as a module, `__name__` equals the module's name instead of "__main__", so the block is skipped.

  20. What is the Python standard library, and why is Python described as coming with "batteries included"?

    It is the large collection of modules (e.g., `math`, `random`, `csv`, `re`, `sys`, `os`) shipped with every Python installation, so common tasks can be done without installing anything — hence "batteries included".

Show the other 30 Python flashcards
  1. Name the standard library functions for picking a random item from a list and a random integer in a range.

    `random.choice(seq)` returns a random element of a sequence; `random.randint(a, b)` returns a random integer $n$ with $a \leq n \leq b$ (both endpoints inclusive).

  2. In Python's `sys` module, what are `sys.argv` and `sys.exit()` used for?

    `sys.argv` is the list of command-line arguments (with `sys.argv[0]` being the program's name); `sys.exit(code)` terminates the program, conventionally with exit status 0 for success and nonzero for error.

  3. What is pip, and what command installs a third-party package with it?

    pip is Python's package installer, which downloads packages from PyPI (the Python Package Index); `pip install package_name` installs a package (e.g., `pip install requests`).

  4. How does a third-party Python library differ from a standard library module?

    Standard library modules ship with Python and can be imported immediately; third-party libraries are written by others, hosted on PyPI, and must be installed (e.g., with pip) before they can be imported.

  5. What is a requirements.txt file used for in a Python project?

    It lists the project's third-party dependencies (one package per line, optionally with versions) so they can all be installed at once with `pip install -r requirements.txt`.

  6. Compare Python lists and tuples: mutability, syntax, and typical use.

    Lists are mutable, written with square brackets `[1, 2, 3]`, used for sequences that change; tuples are immutable, written with parentheses `(1, 2)`, used for fixed collections of values (e.g., coordinates) and are slightly faster/hashable.

  7. 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")`.

  8. 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.

  9. 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).

  10. 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).

  11. 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.

  12. 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.

  13. 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.

  14. 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()`).

  15. 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.

  16. 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.

  17. 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`.

  18. 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`.

  19. 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.

  20. 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`.

  21. 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.

  22. 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.

  23. 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.

  24. 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.

  25. 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.

  26. 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}"`.

  27. 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.

  28. 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.

  29. 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.

  30. 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 ...)`.

CS50x: Introduction to Computer Science Python FAQ

What is in the CS50x: Introduction to Computer Science Python syllabus?

CS50x: Introduction to Computer Science Python is split into 4 chapters: Python Fundamentals, Modules and Libraries, Data and I/O and Advanced Python. Together they contain 13 topics.

How many chapters are in CS50x: Introduction to Computer Science Python?

4 chapters, containing 13 topics. The largest chapter is Python Fundamentals, with 4 topics.

Are there flashcards for CS50x: Introduction to Computer Science Python?

Yes — a 50-card Python deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.