Fall 2026
  • Discord
  • Gradescope
  • Syllabus

On this page

  • Running Python
  • Values and Conditions
  • Collections
  • Functions
  • Loops
  • Testing

Python

We can use a program to do the same calculation for many different inputs. This week we’ll write our first Python programs, use conditions and loops to decide what they do, and test the results.

Running Python

The Python interpreter runs Python code. We can type instructions into it one at a time or run a whole program saved in a file.

Course Setup installed VS Code and Git. Install Python before continuing:

  • macOS: Open Terminal → New Terminal in VS Code and run brew install python. If brew is not found, finish Homebrew’s Next steps in Course Setup.
  • Windows: Install the Python install manager from python.org/downloads or the Microsoft Store. Open a new terminal in VS Code and run python3 once to install Python.
  • Ubuntu or Debian: Run sudo apt install python3 python3-pip python3-venv in a terminal.

Quit and reopen VS Code, then run python3 --version in its terminal. A version number means the interpreter is available.

Running python3 without a filename opens the interactive prompt, or REPL (Read, Eval, Print, Loop). Python reads what you type after >>>, evaluates it, prints the result, and waits for the next instruction.

Try a calculation at the Python prompt:

>>> 17 + 25  # 42

Use exit() to leave Python and return to the terminal. Save the following line in a file named weather.py:

print('Weather report')

Run the file from the terminal in the same folder:

python3 weather.py  # Weather report

A script is a program saved in a file. Python runs it from top to bottom. Use print for results you want to see in the terminal, and save the file before running an edited version.

Values and Conditions

An expression describes a calculation, and its value is the result. A value’s type determines what operations make sense for it. Python uses int for whole numbers, float for numbers with a decimal point, str for text, and bool for the truth values True and False. Strings are written in quotes; the quotes mark the text’s boundaries and are not part of the text itself.

We can calculate the difference between two temperatures and label the result:

print(18 - 12)             # 6
print(7 / 2)               # 3.5
print(type(7))             # <class 'int'>
print(type(7 / 2))         # <class 'float'>
print('cold' + ' morning') # cold morning
print('!' * 3)             # !!!
print(len('frost'))        # 5

An assignment gives a name to a value so later instructions can use it. Python first evaluates the right side of =, then stores that result under the name on the left. Assigning again replaces the name’s previous value. An expression already evaluated does not change when one of its inputs changes later.

morning = 12
evening = morning + 6
morning = 10
print(morning, evening)  # 10 18
morning += 2
print(morning)           # 12

morning += 2 is shorthand for morning = morning + 2. The same update pattern works with -=, *=, //=, and %=. A # begins a comment, which Python ignores through the end of the line. print displays its arguments with a space between them; it does not display the quotes around a string.

A condition is an expression used to decide whether some code should run. Comparisons produce booleans, and and, or, and not combine conditions. An if statement runs its indented block when its condition is true; an optional else block handles the other case. Use four spaces for each indentation level.

The table below shows Python operators and their meanings. (All the cheatsheets from this reading are available as a PDF here.)

Operation Meaning Example
+, -, * Add, subtract, multiply numbers 3 + 2 * 4 is 11
/ Divide; the result is a float 7 / 2 is 3.5
// Divide and round down to a whole number 7 // 2 is 3
% Remainder after division 7 % 2 is 1
** Raise to a power 2 ** 3 is 8
==, != Equal, not equal 3 == 4 is False
<, <=, >, >= Compare values; = includes equality 3 <= 3 is True
and, or, not Both conditions, either condition, reverse a condition 3 > 0 and 3 < 5 is True
+, * on strings Join text, repeat text 'ha' * 2 is 'haha'

Python evaluates powers before multiplication, division, and remainder, then addition and subtraction. Parentheses let you specify which calculation happens first. Use == to compare values; = assigns a value.

temperature = -2
wind = 5
if temperature <= 0 and wind > 0:
    print('cold and windy')  # cold and windy
else:
    print('check the sky')

Conditions can also use values that are not booleans. Zero, an empty string, an empty collection, and None count as false; these are falsey values. Nonzero numbers and nonempty strings and collections are truthy. None represents an absent result. The bool function converts a value to True or False.

and and or stop evaluating once the result is decided. or returns the first operand if it is truthy; otherwise it returns the second. and returns the first operand if it is falsey; otherwise it returns the second.

An empty station name can fall back to a default:

station = ''
label = station or 'home'
print(label)       # home
print(bool(0))     # False
print(not False)   # True

Collections

A single name can hold several related values. A list keeps values in order, so we can select an item by its position. A dictionary associates keys with values, so we can select a value by what it represents. Use a list for a sequence and a dictionary for a record with named fields.

temperatures = [12, 7, 15, 4, 18, 9]
print(temperatures[0])   # 12
print(temperatures[-1])  # 9
print(len(temperatures)) # 6

station = {'name': 'Ridge', 'temperature': 12}
station['temperature'] = 14
print(station['name'], station['temperature'])  # Ridge 14

List indexes start at zero. Negative indexes count backward from the end, with -1 selecting the last item. An index must identify an item that exists. Dictionary keys identify fields rather than positions; a string key needs quotes to distinguish it from a variable name. The in operator tests whether a list contains a value or a dictionary contains a key.

A slice selects a portion of a sequence. It includes its starting index and stops before its ending index. The optional third value sets the step; a negative step moves backward. Leaving out an endpoint selects through the beginning or end in that direction.

temperatures = [12, 7, 15, 4, 18, 9]

print(temperatures[1:4])    # [7, 15, 4]
print(temperatures[:3])     # [12, 7, 15]
print(temperatures[-3:])    # [4, 18, 9]
print(temperatures[4:1:-1]) # [18, 4, 15]
print(temperatures[4:1])    # []
print(sum(temperatures[:3])) # 34

A slice can extend past the end and supplies the items that exist. A slice whose start and stop do not work with its direction is empty. sum, min, and max summarize a collection of numbers. sum([]) is zero; min and max need at least one value to choose from.

The table below shows operations for accessing and summarizing collections.

Operation Meaning
values[i] Item at index i; indexes start at zero
values[-1] Last item
values[start:stop:step] Slice; excludes stop, with a default step of 1
record[key] Dictionary value associated with key
x in values Whether a list contains x
key in record Whether a dictionary contains key
len(values) Number of items
sum(values), min(values), max(values) Total, smallest, largest

A list can contain other lists. Each pair of brackets selects one level, from left to right.

Here each inner list contains a day’s low and high temperatures:

days = [[7, 12], [4, 15], [9, 18]]
print(days[1])     # [4, 15]
print(days[1][0])  # 4

Functions

A function gives a name to a sequence of instructions that we want to reuse. Its parameters are names for the inputs it will receive. Calling the function supplies arguments for those parameters and runs its body. A return statement sends a value back to the calling code and ends that call. Defining a function records its instructions without running them yet.

Save this definition in weather.py, replacing the earlier print statement:

def change(previous, current):
    return current - previous

Add a call below the definition, without indentation:

def change(previous, current):
    return current - previous

print(change(12, 18))  # 6
print(change(18, 12))  # -6

Run python3 weather.py from the terminal. The same instructions handle either pair of observations.

A parameter belongs to its function call. Assigning a new number to that parameter does not reassign a variable in the code that called it. The caller decides what to do with the returned value.

def warmer(temperature):
    temperature += 2
    return temperature

temperature = 12
print(warmer(temperature))  # 14
print(temperature)          # 12

Functions can choose different results with conditions. Each return ends the current call immediately, so later statements in that function are skipped.

Add this definition to weather.py:

def frost_warning(temperature):
    if temperature <= 0:
        return 'frost'
    return 'clear'

print(frost_warning(-2))  # frost
print(frost_warning(8))   # clear

return and print have different jobs. return supplies a value that other code can use; print displays text. A function that finishes without return returns None.

def show_change(previous, current):
    print(current - previous)

result = show_change(12, 18)  # prints 6
print(result)                # None

Loops

A loop repeats instructions. A for loop runs its body once for each item in a sequence. The loop variable takes the next item’s value before each repetition. An accumulator keeps a result built across repetitions, such as a running total or a growing list. Initialize it before the loop, then update it inside the loop.

Create weather_loops.py and add these blocks in order:

rainfall = [2, 0, 5, 1]
total = 0
for amount in rainfall:
    total += amount
print(total)  # 8

range supplies a sequence of integers for a loop. range(stop) starts at zero, while range(start, stop) chooses the start. A third argument sets the step. The stop is excluded in both directions; a range with no items never runs the loop’s body.

for hour in range(0, 7, 3):
    print(hour)  # 0, then 3, then 6

for hour in range(6, 0, -3):
    print(hour)  # 6, then 3

Use for i in range(len(values)) when you need an item’s index as well as its value. The index can also select a corresponding item from another list.

hours = [9, 12, 15]
temperatures = [12, 18, 16]
for i in range(len(hours)):
    print(hours[i], temperatures[i])  # 9 12, then 12 18, then 15 16

A list’s append method adds an item at the end. Combining a loop with a condition lets us filter a collection: keep the items that satisfy a rule. The resulting list starts empty and grows when an item passes the condition. append changes the list and returns None.

temperatures = [3, -2, 7, 0, -1]
frost = []
for temperature in temperatures:
    if temperature <= 0:
        frost.append(temperature)
print(frost)  # [-2, 0, -1]

sorted(values) returns a new list in ascending order and leaves the original alone. The method values.sort() instead reorders the original list and returns None. A slice can select part of either result.

temperatures = [3, -2, 7, 0, -1]

ranked = sorted(temperatures)
print(ranked[:2])    # [-2, -1]
print(temperatures)  # [3, -2, 7, 0, -1]

A nested loop runs one loop inside another. For each item selected by the outer loop, the inner loop runs all of its repetitions. This lets us visit every item in a collection of collections.

days = [[7, 12], [4, 15], [9, 18]]
all_temperatures = []
for day in days:
    for temperature in day:
        all_temperatures.append(temperature)
print(all_temperatures)  # [7, 12, 4, 15, 9, 18]

A while loop repeats as long as its condition is truthy. It checks the condition before each repetition, including the first. The body usually updates a value used in that condition so the loop can eventually stop. If a loop keeps running, Ctrl+C stops the program in the terminal.

minutes = 3
while minutes > 0:
    print(minutes)  # 3, then 2, then 1
    minutes -= 1
print('take a reading')  # take a reading

Loops can also be part of a function. Put return after the loop when the result needs all its repetitions; returning inside the loop ends the call during that repetition.

Add this definition to weather.py:

def frost_count(temperatures):
    count = 0
    for temperature in temperatures:
        if temperature <= 0:
            count += 1
    return count

print(frost_count([3, -2, 7, 0, -1]))  # 3
print(frost_count([]))                # 0

The completed weather functions and loop experiments are available for comparison.

Testing

A test runs part of a program and checks the result against the one we expect. For a function with several branches, choose inputs that reach each branch. Include values right at the boundary, where it’s easy to mix up < and <=.

A doctest records a function call and its expected result inside the function’s documentation. The triple-quoted text immediately below def is its docstring. Doctest examples use the REPL format: >>> before the call, followed by its expected result on the next line.

Replace the frost_warning definition in weather.py with this version:

def frost_warning(temperature):
    '''Describe whether the temperature is at or below freezing.

    >>> frost_warning(-2)
    'frost'
    >>> frost_warning(0)
    'frost'
    >>> frost_warning(8)
    'clear'
    '''
    if temperature <= 0:
        return 'frost'
    return 'clear'

Remove the standalone print calls from weather.py, leaving its function definitions. Run the tests from the terminal:

python3 -m doctest weather.py     # no output when all tests pass
python3 -m doctest -v weather.py  # shows each check and a final count

Now deliberately change temperature <= 0 to temperature < 0 and rerun the tests. The zero-degree test fails: its Expected value is 'frost', but its Got value is 'clear'. The negative and positive examples still pass. Restore <= and rerun to check the repair.

-m doctest asks Python to run its built-in doctest module on the named file. A failed doctest reports the call, the expected result, and the actual result so you can trace the disagreement. When someone supplies tests for a function, use them to understand its required behavior and check your implementation.