Breaking programs into smaller pieces.
Data 94, Spring 2021 @ UC Berkeley
Suraj Rampure, with help from many others
Functions
5
Overview
Announcements
Functions
Motivation
We’ve used a few of Python’s built-in functions so far.
int('-14') # Evaluates to -14
abs(-14) # Evaluates to 14
max(-14, 15) # Evaluates to 15
print('zoology') # Prints zoology, evaluates to None
These functions return a value or have some side effect (e.g. printing).
Motivation
Right now, if we want to perform a calculation for different values, we need to copy-and-paste our code.
We’re performing the same computation for all three students.
Functions
Functions are a way to divide our code into small subparts to prevent us from writing repetitive code.
def ready_to_graduate(year, units):
return (year == 'senior') and (units >= 120)
ready_to_graduate('senior', 121) # Evaluates to True
ready_to_graduate('sophomore', 109) # Evaluates to False
Defining new functions
All function definitions use the same syntax structure.
def ready_to_graduate(year, units):
return (year == 'senior') and (units >= 120)
def is a keyword in Python. It means “define”.
ready_to_graduate is the name of our new function.
Our function has two parameters: year and units.
After the first line, we must indent using 4 spaces or one tab.
The return keyword determines what our function outputs.
Parameters
Parameters are the variables that a function requires as an input, that are defined in its “signature”.
Parameters are placeholders for the values that will be passed into the function when it is called.
# This function has one parameter, x.
# When we call the function, the value we pass in
# as an argument will replace x in the computation.
def triple(x):
return x*3
When we call triple(-15), you can pretend that there’s an invisible line in the body of triple that says x = 15.
Examples
# Functions can have zero parameters!
def always_true():
return True
# The body of a function can be
# longer than one line.
def pythagorean(a, b):
c_squared = a**2 + b**2
return c_squared**0.5
Indentation
This is the first time we’ve written code where indentation is required.
Fortunately, when defining a function in a Jupyter Notebook, indentation usually happens automatically.
Quick Check 1
Suppose we define the function mystery as follows.
def mystery(t):
return t + '0'
What will be the values of alpha, beta, and charlie after running the following code? If the call errors, write Error.
alpha = mystery('19')
beta = mystery(19)
charlie = mystery('1' + '9')
Scoping, parameters, and return values
Scoping
The names you choose for a function’s parameters are only known to that function (known as “local scope”). The rest of your notebook is unaffected by parameter names.
Scoping
Similarly, you can choose parameter names that also exist as variable names outside of your function.
We do this sometimes, but it can get confusing.
When half(0) is called, from the perspective of half, N is equal to 0.
Scoping
You can also use variables that don’t overlap with parameter names within your function.
In such cases, the function looks “outside” of its definition to the rest of your notebook to see if it can find that variable anywhere.
Operands are evaluated first
Remember, operands are evaluated first to determine the arguments. If an error occurs when evaluating an operand, the function will not be called.
Be careful...
If you call a function with the wrong number of arguments, Python will give you an error.
Some functions, like print and min, can take a variable number of arguments. We’ll see how to define these later.
A word on vocabulary
This is not a class where you should try and memorize vocabulary. With that said, things may be a little hazy.
def minmax(a, b, c):
return min(a, b) == max(b, c)
result = minmax(3, 3 + 4, int(True))
Return values
Functions are not required to “return” anything. If a function doesn’t explicitly return anything, it will return None (like print).
Return statements
Once we reach a return keyword, our function is done running. Nothing after it is run.
Quick Check 2
What is the value of total after running this code?
total = 3
def square_and_cube(a, b):
return a**2 + total**b
total = square_and_cube(1, 2)
Quick Check 2
Followup: what is the value of total after running this code?
total = 3
def square_and_cube(a, b):
return a**2 + total**b
total = square_and_cube(1, 2)
total = square_and_cube(1, 2)
total is 101.
String methods
Methods
Methods are functions with slightly different syntax.
'isaac'.upper() # Evaluates to 'ISAAC'
Methods use “dot notation”.
In our class, we will not write any methods of our own; we’ll only write functions of our own.
However, many of the data types we will deal with have built-in methods that we will use.
String methods
For now, here are some methods that work on strings that you should know.
Assume that the line s = 'JuNiOR12' has been run.
There are many more, but we will use them as they become relevant.
Method | Example Usage | Example Value |
upper | s.upper() | 'JUNIOR12' |
lower | s.lower() | 'junior12' |
replace | s.replace('i', 'iii') | 'JuNiiiOR12' |
Demo
We can do a lot with what we’ve learned so far!
Summary, next time
Summary
Next time
Announcements