CIS 2020 · Python for Everyone · Module 10 · Study guide

Module 10 review: functions and CSV files

A function is a named piece of code that does one job. You have been calling functions since your first program: print(), input(), and len() are all functions somebody else wrote. This module shows you how to use a function without knowing what is inside it, how to write and test your own, how values travel in through parameters, and how results come back out with return. The last section uses a function to read a CSV file. Every example prints its result, so run each one and check your prediction.

Section 5.1

Functions as Black Boxes

You can use a function without knowing how it works inside. You only need to know what to give it and what it gives back.

A function as a black box The arguments 3.14159 and 2 go into a dark box labeled round. The inside of the box is hidden. The return value 3.14 comes out the other side. arguments go in 3.14159, 2 round inside is hidden return value comes out 3.14 round(3.14159, 2) gives back 3.14
The values you pass in are arguments. The value the function hands back is its return value. How it gets from one to the other is the function's business, not yours.

You already use black boxes

Think about a microwave. You put in food and a time, press start, and get hot food back. You do not need to understand how microwaves heat water to use one. Functions work the same way.

print(round(3.14159, 2))
print(abs(-7))
print(max(4, 9, 2))
print(len("hello"))
3.14
7
9
5

None of these programs show how rounding, absolute value, or finding a maximum actually works. You give each function its arguments inside the parentheses, and it gives you a result.

Save a return value in a variable

A function call is replaced by its return value, so you can store it, print it, or use it in a bigger expression.

price = 19.987
rounded = round(price, 2)
print("Rounded price:", rounded)

biggest = max(12, 45, 7)
print("Twice the biggest:", biggest * 2)
Rounded price: 19.99
Twice the biggest: 90

Functions from a module

Some functions live in a module you must import first. The math module is a box full of math functions.

import math

print(math.sqrt(16))
print(math.floor(7.8))
print(math.ceil(7.2))
4.0
7
8
To use a black box, you only need its description
CallArgumentsReturns
round(x, digits)a number and how many decimal placesthe rounded number
abs(x)a numberthe number without a minus sign
max(a, b, c)two or more valuesthe largest one
len(s)a string or listhow many items it has
math.sqrt(x)a numberits square root, as a float

Why this matters: once you write a function and know it works, you can treat it as a black box too. You stop thinking about its insides and just use it, which keeps big programs manageable.

Section 5.2

Implementing and Testing Functions

Now you build the box. Writing a function takes three decisions: what to name it, what it needs to know (its parameters), and what it should give back (its return value).

Your first function

def rectangle_area(width, height):
    area = width * height
    return area

print(rectangle_area(3, 4))
12

Here is every part, one at a time:

Defining is not running. The def block only teaches Python a new word. Nothing inside it runs until a line like rectangle_area(3, 4) calls it. A program with a def and no call prints nothing at all.

Call it as many times as you like

def rectangle_area(width, height):
    area = width * height
    return area

print(rectangle_area(3, 4))
print(rectangle_area(10, 2))
print(rectangle_area(2.5, 4))
12
20
10.0

One definition, three calls. This is the main reason to write a function: write the steps once, use them anywhere.

Describe it with a comment

A short comment right under the header tells the reader what goes in and what comes out, the same information you used for the black boxes in Section 5.1. A string in triple quotes in that spot is called a docstring.

def rectangle_area(width, height):
    """Computes the area of a rectangle.
    width and height are the side lengths.
    Returns width times height.
    """
    area = width * height
    return area

Test with values you can check by hand

Before you trust a function, call it with inputs where you already know the answer. Print the expected value next to the actual one so a mistake jumps out.

def fahrenheit_to_celsius(fahrenheit):
    celsius = (fahrenheit - 32) * 5 / 9
    return celsius

print(fahrenheit_to_celsius(32), "expected 0.0")
print(fahrenheit_to_celsius(212), "expected 100.0")
print(fahrenheit_to_celsius(-40), "expected -40.0")
print(round(fahrenheit_to_celsius(98.6), 1), "expected 37.0")
0.0 expected 0.0
100.0 expected 100.0
-40.0 expected -40.0
37.0 expected 37.0

Freezing, boiling, and minus 40 (where both scales match) are easy to check. Pick test values that include ordinary cases and edge cases such as zero or a negative number.

Find a bug by testing

def average_of_two(a, b):
    return a + b / 2

print(average_of_two(4, 6), "expected 5.0")
7.0 expected 5.0

The test caught it. Division happens before addition, so this computed 4 + 3. The fix is parentheses: return (a + b) / 2.

Organize the program with main()

As programs grow, put the main steps in a function called main and call it on the last line. Then the order of your other functions does not matter, because by the time main() runs, Python has read every definition.

def main():
    width = float(input("Width: "))
    height = float(input("Height: "))
    print("Area:", rectangle_area(width, height))

def rectangle_area(width, height):
    area = width * height
    return area

main()
Width: 5
Height: 3
Area: 15.0

Common mistake: calling a function above its def. Python reads your file from top to bottom, so print(rectangle_area(3, 4)) on line 1 with the def below it gives NameError: name 'rectangle_area' is not defined. The main() pattern avoids this.

Section 5.3

Parameter Passing

When you call a function, each argument's value is copied into the matching parameter variable. The function works with its own copy.

An argument value is copied into a parameter variable On the left, the caller has a variable named value holding 5. An arrow labeled copy points to the function double on the right, where the parameter variable number starts at 5 and is then changed to 10. The caller's value is still 5. the caller value 5 still 5 after the call copy inside double(number) number 5 10 changed copy
Changing a parameter variable changes only the function's copy. The caller's variable is left alone.

Trace a call step by step

def double(number):
    number = number * 2
    return number

value = 5
result = double(value)
print("value:", value)
print("result:", result)
value: 5
result: 10
  1. value is set to 5.
  2. double(value) is called. The parameter variable number is created and gets a copy of 5.
  3. Inside the function, number becomes 10. Only the copy changes.
  4. return number sends 10 back, and it is stored in result. The function's number disappears.

An argument can be any expression

def double(number):
    return number * 2

print(double(7))
print(double(3 + 4))
print(double(len("cat")))
print(double(double(2)))
14
14
6
8

Python works out the argument first, then passes the result. In the last line the inner call runs first and returns 4, then double(4) returns 8.

Several parameters are matched by position

def describe_pet(name, kind):
    print(name, "is a", kind)

describe_pet("Rex", "dog")
describe_pet("dog", "Rex")
Rex is a dog
dog is a Rex

The first argument goes into the first parameter, the second into the second. Python does not know which one you meant, so the order you write them in is the order they arrive.

The argument count must match

def rectangle_area(width, height):
    return width * height

print(rectangle_area(5))
TypeError: rectangle_area() missing 1 required positional argument: 'height'

Parameter names belong to the function

A parameter variable exists only while its function runs. The caller's variable names do not need to match it at all.

def greet(person):
    print("Hello,", person)

student = "Maya"
greet(student)
greet("Luis")
Hello, Maya
Hello, Luis

The caller has student and the function has person. The value travels; the name does not.

Common mistake: asking for input inside the function and ignoring the parameter.

def square(n):
    n = int(input("Enter a number: "))   # wrong: throws away the argument
    return n * n

Now square(4) ignores the 4. Let the caller get the input and pass it in; the function should just use n.

Section 5.4

Return Values

The return statement does two things at once: it sends a value back to the caller, and it ends the function immediately.

Use the result right away

def rectangle_area(width, height):
    return width * height

total = rectangle_area(2, 3) + rectangle_area(4, 5)
print("Total area:", total)
Total area: 26

Each call is replaced by its return value, 6 and 20, so the line works out to 6 + 20.

return ends the function

def greet():
    return "Hi"
    print("This line never runs")

print(greet())
Hi

Different branches can return different values

def letter_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

print(letter_grade(95))
print(letter_grade(85))
print(letter_grade(72))
print(letter_grade(41))
A
B
C
F

As soon as one return runs, the function is done, so only one grade comes back per call.

Return a True or False answer

def is_even(number):
    return number % 2 == 0

print(is_even(4))
print(is_even(7))

if is_even(10):
    print("10 is even")
True
False
10 is even

A function that answers a yes or no question can return the condition itself. Name it like a question, such as is_even or has_digit, and it reads naturally in an if.

Printing is not returning

This is the most common mix up with functions. Compare these two:

def show_double(n):
    print(n * 2)

def get_double(n):
    return n * 2

answer = get_double(5) + 1
print("answer:", answer)

answer = show_double(5) + 1
answer: 11
10
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

show_double puts 10 on the screen, but gives nothing back to the program, so there is nothing to add 1 to. If you need to use the answer later, return it. Print only when the job is to show something to the user.

Forgetting return gives you None

def add(a, b):
    total = a + b

result = add(2, 3)
print(result)
None

The function computed 5 and then threw it away. A function that reaches its last line without a return gives back the special value None, which means "nothing." Add return total to fix it.

Make sure every path returns

def describe_temp(degrees):
    if degrees > 80:
        return "hot"
    elif degrees < 50:
        return "cold"

print(describe_temp(95))
print(describe_temp(65))
hot
None

For 65, neither condition is true, so the function falls off the end and returns None. Add an else with return "mild" so every possible input gets an answer.

Trace it: for each test value, follow the code and ask "which return runs?" If the answer is "none of them," you found a missing case.

Section 7.1

Working with CSV Files

A CSV file is a table saved as plain text: one row per line, with commas between the columns. Python's built in csv module reads each row as a list of strings.

Full lesson: Section 7.1 has its own page with more than 30 short examples, starting with plain text files and building up to CSV files step by step. Read Section 7.1: reading and writing files, and working with CSV files, or jump straight to the CSV part if you are already comfortable with text files.

Functions and CSV files together

Here is one example that uses everything from this module. Save this file next to your program:

students.csv

name,score
Ana,88
Ben,92
Chloe,75
import csv

def average_score(filename):
    """Reads a CSV file with a header and a score column.
    Returns the average of the scores.
    """
    total = 0
    count = 0
    with open(filename, "r", newline="") as file:
        reader = csv.reader(file)
        next(reader)   # skip the header row
        for row in reader:
            total = total + int(row[1])
            count = count + 1
    return total / count

def main():
    average = average_score("students.csv")
    print("Class average:", round(average, 1))

main()
Class average: 85.0

The file name is a parameter, so the same function works for any file with the same layout. The function returns the average instead of printing it, so main() decides how to round and display it. Once you have tested it, average_score is a black box: give it a file name, get back a number.

Quick check

If you remember only these

  • A function is a black box: you need to know its arguments and its return value, not its insides.
  • Arguments are the values in the call; parameter variables are the names in the def line that receive them.
  • A def block runs only when the function is called. Define a function before the line that calls it, or use the main() pattern.
  • Test a function with inputs whose answers you can work out by hand, including edge cases like 0 and negative numbers.
  • Each argument's value is copied into its parameter. Changing the parameter does not change the caller's variable.
  • Arguments are matched to parameters by position, and the count must match.
  • return sends a value back and ends the function immediately.
  • Printing shows a value to the user; returning gives it to the program. A function without return gives back None.
  • Make sure every path through an if chain reaches a return.
  • For CSV files: import csv, open with newline="", use csv.reader, and skip the header with next().