Skip to content

Oct 21: Review Chapters 1–8

Learning Objectives

After today's class, you should be able to:

  • Write programs that use topics from the first 8 chapters.
  • Run pytest using the -k option to isolate test functions.
  • Describe how requirements are verified by autograders.

Announcements

  • PA 1 FlexDoko (modules + testing)
    • Readiness Quiz due Tuesday 10/22 (10 pts)
    • Part 1 utilities.py due Friday 10/25 (30 pts)
    • Part 2 game_logic.py due Tuesday 10/29 (60 pts)
  • Withdraw deadline: Wed, Oct 23rd
    • If you are getting a D or F, consider withdrawing
    • Please come and talk to me during office hours!

Development Environment

If you have not set up VS Code or pytest, please do so today!

Review Activity

Setup

  • Create a folder named review (in your CS149 folder)
  • Create new files named ch1.py, ch2.py, …, ch7.py
  • Download the provided test modules:

Instructions

  • Work together to complete the review exercises below
  • The bullet points provide a few hints; not all are needed
  • After each exercise, run the corresponding test function
    pytest -q -k test_ch1
    

Chapter 1: Statements

  • print() with sep= and end=
  • input() with/without prompt
  • escape sequences (Ex: \n)

Exercise 1 (ch1.py)

On Canvas, the User Settings page shows both a Display Name (Ex: Ada Lovelace) and a Sortable Name (Ex: Lovelace, Ada). Write a program that inputs first and last names, and then prints the corresponding Display Name and Sortable Name, separated by a slash:

First name: Ada
Last name: Lovelace
Ada Lovelace / Lovelace, Ada

Your program may not use f-strings, may not use the + operator, and must have two print statements: one for Display Name, and one for Sortable Name.

Chapter 2: Expressions

  • f-strings, format specs
  • arithmetic operators
  • The math module

Exercise 2 (ch2.py)

Write a program that inputs \(a\), \(b\), and \(c\) as floats and solves the equation \(ax^2 + bx + c = 0\) using the quadratic formula:

\[x = {-b \pm \sqrt{b^2 - 4ac} \over 2a}\]

The program should display no prompts and output the two results on separate lines. Each result should be formatted to three decimal places as shown:

1
4
-21
3.000
-7.000

Chapter 3: Branches

  • if, elif, else
  • and, or, not
  • operator precedence

Exercise 3 (ch3.py)

Interstate highways in the United States use a numbering system based on their direction. North-south routes are assigned odd numbers, and east-west routes are assigned even numbers.

Write a program that inputs an integer between 1 and 99. No prompt should be displayed. You do not have to check if the input is within range. The program should output one line, using only one print statement. The possible outputs are:

Input Output
even integer not a multiple of 5 east-west
even integer and a multiple of 5 east-west coast-to-coast
odd integer not a multiple of 5 north-south
odd integer and a multiple of 5 north-south border-to-border

Your code may not use [] to index the input like a string. Your code must use nested if statements—the and operator is not allowed. The elif keyword is also not allowed.

Chapter 4: Functions

  • def, return, None
  • global vs local scope
  • docstrings and help()

Exercise 4 (ch4.py)

Rewrite your solution to Exercise 2 as a function:

  • Define a function named quadratic that takes three floats as parameters.
    • You don't need to read the floats using input(), because the floats are passed to the function.
  • Apply the quadratic formula, and return the results as a tuple of two floats.
    • You don't need to display the results using print(), because the results are returned from the function.
    • You don't need to format the results to three decimal places, because the results aren't being printed.

For example, quadratic(1, 4, -21) should return (3, -7).

Chapter 5: Containers

  • list, tuple, set, dict
  • in, not in, is, is not
  • min(), max(), sum()

Exercise 5 (ch5.py)

Implement the following functions with one line of code each. Your code may not use any if statements or for/while loops.

def is_valid(color):
    """Determine whether a tuple is a valid RGB color.

    Args:
        color (tuple): 3 integers that represent (red, green, blue)

    Returns:
        bool: True when each integer is between 0 and 255 (inclusive)
    """
Hint for is_valid: Use min() and max()

def is_unique(numbers):
    """Determine whether all the numbers in a list are unique.

    Args:
        numbers (list): integers to consider (can be any length)

    Returns:
        bool: True when the numbers list contains no duplicate values
    """
Hint for is_unique: Use len() and set()

Chapter 6: For Loops

  • for variable in iterable
  • range with 1, 2, or 3 values
  • enumerate() – index, value

Exercise 6 (ch6.py)

Implement the following function:

def count_words(text, magic):
    """Count the number of magic words in a sentence.

    Args:
        text (str): a sentence (all lowercase, no punctuation)
        magic (set): words that are known to have magical power

    Returns:
        int: how many words in text are in the magic word set
    """
Hint for count_words: Use the str.split() method.

Chapter 7: While Loops

  • while condition
  • break and continue
  • The random module

Exercise 7 (ch7.py)

Write a program (not a function) that reads input from the user, one line at a time, until the user inputs STOP. No prompts should be displayed. Whenever the user inputs a line that contains super, the program should output duper!. For example (user input in bold font):

Hello, everyone.
I hope you have a super day.
duper!
Best regards,
–superman
duper!
STOP

Chapter 8: Unit Testing

Exercise 8 (test_review.py)

As a team, discuss the provided test code.

  • The tests for chapters 1–3 and 7 use run_module() to capture output printed to the screen.
  • The tests for chapters 4–6 import the module and call the functions directly to get the result.

Answer the following questions as a team:

  1. How is testing programs that print output different from testing functions?
  2. What techniques demonstrated in test_review.py can be applied to PA1?