Week 6 (Python)


  • Python
  • Python syntax
  • Pythonic implementations of…
    • Loops (e.g., range)
    • Hash tables (e.g., dicts)
    • Arrays (e.g., lists)
    • Strings (e.g., strs)
  • Python’s dot syntax for functions (e.g., str.strip)

Suggested Syntax to Show

  • Python loops. (for, while, using range to loop a certain number of times, using len to get the length of a list or a string to determine how many times to loop).
  • Python dictionaries.
    • Create a dictionary with x = dict()
    • Set a key and value with x["foo"] = "bar"
    • Get a key from the dictionary with x["foo"]
  • Python strings.
    • Getting the length of a string with len(s)
    • Getting a substring from a string with s[i:j]

Programming Exercises

Below are a few example programming exercises that engage students in hands-on practice on the week’s topics. Keep in mind that class might not be long enough to include all exercises, so be sure to pick just a few! For this week, in particular, you might choose one exercise from each of these topics.

Several of these are re-implementations of exercises already done in C! Feel free to do the same for any other C exercises you’ve used in past weeks; the goal for this week is to get comfortable translating ideas from C into Python.

  • Reverse
    • Write a program reverse.py that reverses a string.
    • Topics
      • Strings
      • String manipulation in Python
    • Sample Usage
      $ python reverse.py
      Text: This is CS50
      05SC si sihT
    • Sample Solution
      from cs50 import get_string
      s = get_string("Text: ")
      for i in range(len(s)):
          print(s[len(s) - i - 1], end="")
  • Addition
    • Write a program addition.py that adds two numbers provided as command-line arguments.
    • Topics
      • Command-line arguments
    • Sample Usage
      $ python addition.py 2 8
      2 + 8 = 10
    • Sample Solution
      import sys
      if len(sys.argv) != 3:
          sys.exit("Usage: python addition.py x y")
      x = int(sys.argv[1])
      y = int(sys.argv[2])
      print(f"{x} + {y} = {x + y}")
  • Factorial
    • Write a function factorial that computes the factorial of a number.
      • First, write the function using a loop, and without using recursion.
      • Then, re-write the function to be recursive, without using a loop.
    • Topics
      • Functions
      • Loops
      • Recursion
    • Non-Recursive Sample Solution
      def factorial(n):
          result = 1
          for i in range(1, n + 1):
              result *= i
          return result
    • Recursive Sample Solution
      def factorial(n):
          if n == 0:
              return 1
          return n * factorial(n - 1)
  • Copy
    • Write a program copy.py that copies a text file, where the name of the original file and the copied file are specified as command-line arguments.
    • Topics
      • File I/O
      • read
    • Sample Usage
      $ python copy.py input.txt output.txt
    • Sample Solution
      import sys
      if len(sys.argv) != 3:
          sys.exit("Usage: python copy.py infile outfile")
      infile = open(sys.argv[1])
      outfile = open(sys.argv[2], "w")
      contents = infile.read()
    • As a possible extension to this exercise, modify the input file in some way (capitalizing it, replacing some text with some other text, etc.) before writing it to the output file.
  • Phonebook
    • Write a program phonebook.py that reads from a CSV file (provided as a command-line argument) and prints out the data on each person in the phone book. The file contains columns name and number, representing each person’s name and phone number, respectively.
    • As a next step, add some error checking to ensure that (1) the program is run with a command-line argument, and (2) the CSV file contains both a name column and a number column.
    • Topics
      • File I/O
      • DictReader
      • Dictionaries
    • Sample File
    • Sample Usage
      $ python phonebook.py data.csv
      Emma's phone number is 617-555-0100
      Rodrigo's phone number is 617-555-0101
      Brian's phone number is 617-555-0102
      David's phone number is 617-555-0103
    • Sample Solution
      import csv
      import sys
      if len(sys.argv) != 2:
          sys.exit("Usage: python phonebook.py data.csv")
      f = open(sys.argv[1])
      reader = csv.DictReader(f)
      fields = reader.fieldnames
      if "name" not in fields or "number" not in fields:
          sys.exit("File must have name and number columns")
      for row in reader:
          name = row["name"]
          number = row["number"]
          print(f"{name}'s phone number is {number}")

Conceptual Exercises

These exercises involve thinking and problem-solving, though writing a program is less of the focus here. They still engage students in practice that helps them better understand the week’s concepts!

  • str Prediction
    • Students should open str_prediction.py and read through the code without running the program. Students should predict which strings will be printed for each round of string manipulation. Once they’ve done so, they can discuss their predictions with classmates and run the file itself to test the accuracy of their predictions.
    • For those feeling more comfortable, or who finish early, they can add another round of string manipulation that prints a string backwards using the range function.

Annotated Sample Slides

Here you’ll find sample slides to adopt or adapt when teaching Week 6.

Some slides contain speaker notes to illustrate why the sample slides take a certain approach to illustrating a concept or leading an exercise. You’re welcome to modify these slides as you see fit, though do try to keep some of the same elements of active learning that have been included in these samples.

Past versions of sample slides are also available under the “Additional Slide Resources” dropdown.