1 of 31

Breaking programs into smaller pieces.

Data 94, Spring 2021 @ UC Berkeley

Suraj Rampure, with help from many others

Functions

5

2 of 31

Overview

Announcements

  • User-defined functions.
  • Scoping, parameters, and return values.
  • String methods.
  • Homework 1 was released yesterday, and is due on Wednesday at 11:59PM!
    • Includes topics from MWF this week.
    • See Ed for submission instructions.
    • We’ll help you get started in lab, right after this.
    • Post any questions in the “Homework 1 Questions” thread on Ed!
  • Do Survey 1 as well!

3 of 31

Functions

4 of 31

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).

5 of 31

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.

6 of 31

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

7 of 31

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.

8 of 31

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

9 of 31

When we call triple(-15), you can pretend that there’s an invisible line in the body of triple that says x = 15.

10 of 31

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

11 of 31

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.

12 of 31

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')

13 of 31

Scoping, parameters, and return values

14 of 31

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.

15 of 31

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.

16 of 31

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.

17 of 31

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.

18 of 31

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.

19 of 31

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))

  • Parameters: a, b, c.
  • Operands: 3, 3 + 4, int(True).
  • Arguments: 3, 7, 1.

20 of 31

Return values

Functions are not required to “return” anything. If a function doesn’t explicitly return anything, it will return None (like print).

21 of 31

Return statements

Once we reach a return keyword, our function is done running. Nothing after it is run.

22 of 31

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)

23 of 31

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.

  • After square_and_cube(1, 2) is evaluated and assigned to total, total is 10.
  • When square_and_cube(1, 2) is evaluated the second time, total is 10, so the new calculation is 1**2 + 10**2, which is 101.

24 of 31

String methods

25 of 31

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.

26 of 31

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'

27 of 31

Demo

28 of 31

We can do a lot with what we’ve learned so far!

29 of 31

Summary, next time

30 of 31

Summary

  • Functions are a way to divide our code into small subparts to prevent us from writing repetitive code.
    • The inputs to a function are known as parameters.
    • To specify a function’s output, we use the return keyword.
  • Parameters are a little nuanced:
    • They are only visible to the body of your function; the rest of your notebook can’t use them.
    • Operands are evaluated before being passed into your function.
  • Methods are like functions. String methods help us manipulate strings.

31 of 31

Next time

Announcements

  • Control: using boolean expressions to control which parts of our code are run.
  • If statements and if-else.
  • Elif.
  • Truthy values.
  • Demo.
  • Don’t forget to follow along with the Quick Checks on Ed!
  • Homework 1 was released yesterday, and is due on Wednesday at 11:59PM!
    • We’ll help you get started in lab, right after this.
    • Post any questions in the Homework 1 thread on Ed!
    • Office hours on Monday and Wednesday next week.