CIS 2020 · Python for Everyone · Module 10 · Study guide
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
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.
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.
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
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
| Call | Arguments | Returns |
|---|---|---|
| round(x, digits) | a number and how many decimal places | the rounded number |
| abs(x) | a number | the number without a minus sign |
| max(a, b, c) | two or more values | the largest one |
| len(s) | a string or list | how many items it has |
| math.sqrt(x) | a number | its 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
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).
def rectangle_area(width, height):
area = width * height
return area
print(rectangle_area(3, 4))
12
Here is every part, one at a time:
def starts a function definition. It means "define."rectangle_area is the name. Use a clear description in lowercase with underscores, just like a variable name.(width, height) are the parameter variables. They hold the values the caller sends in.return area sends the answer back to whoever called the function.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.
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.
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
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.
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.
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
When you call a function, each argument's value is copied into the matching parameter variable. The function works with its own copy.
def double(number):
number = number * 2
return number
value = 5
result = double(value)
print("value:", value)
print("result:", result)
value: 5 result: 10
value is set to 5.double(value) is called. The parameter variable number is created and gets a copy of 5.number becomes 10. Only the copy changes.return number sends 10 back, and it is stored in result. The function's number disappears.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.
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.
def rectangle_area(width, height):
return width * height
print(rectangle_area(5))
TypeError: rectangle_area() missing 1 required positional argument: 'height'
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
The return statement does two things at once: it sends a value back to the caller, and it ends the function immediately.
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 functiondef greet():
return "Hi"
print("This line never runs")
print(greet())
Hi
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.
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.
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.
return gives you Nonedef 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.
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
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.
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.
def line that receive them.def block runs only when the function is called. Define a function before the line that calls it, or use the main() pattern.return sends a value back and ends the function immediately.return gives back None.if chain reaches a return.import csv, open with newline="", use csv.reader, and skip the header with next().