1 of 47

CSE 160

Functions

Hannah Cheung

2 of 47

Announcements

  • HW0 grades released
    • Resubmissions open! (+ tutorial)
    • Regrades open! (+ tutorial)
  • Due Friday (7/1) @ 11:59 PM:
    • HW1 due
    • Submit programming + reflection survey
  • Due Wednesday (7/6) @ 11:59 PM:
    • CodingBat #1 Problems due
    • Resubmissions and regrades do not apply here!
  • Due Friday (7/8) @ 11:59 PM:
    • HW2 due
    • DNA processing using loops, if statements, functions, and string manipulation

2

3 of 47

Math Functions

  • Math uses functions
    • Defining functions: f(x) = 2x + 1
    • Using functions: f(2) = 5
  • Python lets you use and define functions
    • We have already seen some Python functions:

len, float, int, str, range

3

4 of 47

Python Functions

  • Function packages up and names a computation
  • Advantages to using functions
    • Through parameters, generalizes computation to other scenarios
    • Reduces repetition in programs
    • Makes programs easier to understand and easier to modify and debug

4

5 of 47

Using (Calling) Functions

len(“hello”)

len(“”)

math.sqrt(9)

math.sqrt(7)

range(1, 5)

range(8)

math.sin(0)

str(17)

random.random()

print()

5

  • Functions can take in zero or more inputs
  • All of the functions here return a value
  • Get to re-use code that someone else wrote

6 of 47

Function call examples

import math

x = 8

y = 16

z = math.sqrt(16)

u = math.sqrt(y)

v = math.sqrt(8 + 8)

w = math.sqrt(x + x)

6

What are the

  • function calls or “function invocations” or “call sites”?
  • arguments or parameters for each function call?

7 of 47

Function call examples

greeting = “hi”

name = “Hannah”

a = len(“hello”)

b = len(greeting)

c = len(“hello” + “Hannah”)

print(“hello”)

print()

print(len(greeting + name))

7

What are the

  • function calls or “function invocations” or “call sites”?
  • arguments or parameters for each function call?

8 of 47

Function call examples

greeting = “hi”

name = “Hannah”

a = len(“hello”)

b = len(greeting)

c = len(“hello” + “Hannah”)

print(“hello”)

print()

print(len(greeting + name))

8

What are the

  • function calls or “function invocations” or “call sites”?
  • arguments or parameters for each function call?

  • math.sqrt() and len take an input and return a value.
  • print produces a side effect (prints to terminal).

9 of 47

Some functions are like a machine

9

  • Given an input
  • Produces a result or “returns” a value

2x + 1

2x + 1

2x + 1

x

x

x

2

0

100

5

f(x)

1

f(x)

201

f(x)

10 of 47

Defining a function

def dbl_plus(x):

return 2 * x + 1

10

keyword that defines function

2x + 1

x

f(x)

11 of 47

Defining a function

def dbl_plus(x):

return 2 * x + 1

11

keyword that defines function

2x + 1

x

f(x)

name of function

12 of 47

Defining a function

def dbl_plus(x):

return 2 * x + 1

12

keyword that defines function

2x + 1

x

f(x)

name of function

input variable name or parameter

13 of 47

Defining a function

def dbl_plus(x):

return 2 * x + 1

13

keyword that defines function

2x + 1

x

f(x)

name of function

input variable name or parameter

keyword that specifies result

14 of 47

Defining a function

def dbl_plus(x):

return 2 * x + 1

14

keyword that defines function

2x + 1

x

f(x)

name of function

input variable name or parameter

keyword that specifies result

return expression (part of return statement)

15 of 47

Executing a function call

def square(x):

return x * x

square(3 + 4)

15

Function definition

Function call

16 of 47

Executing a function call

def square(x):

return x * x

square(3 + 4)

square(3 + 4)

square(7)

16

Function definition

Function call

  1. Evaluate argument(s) at call site - place where we are calling function from in program

17 of 47

Executing a function call

def square(x):

return x * x

square(3 + 4)

square(3 + 4)

square(7)

17

Function definition

Function call

  • Evaluate argument(s) at call site - place where we are calling function from in program
  • Assign argument’s value to the formal parameter name
  • A new variable, not a reuse of any existing variable of the same name

x: 7

18 of 47

Executing a function call

def square(x):

return x * x

square(3 + 4)

square(3 + 4)

square(7)

18

Function definition

Function call

  • Evaluate argument(s) at call site - place where we are calling function from in program
  • Assign argument’s value to the formal parameter name
  • A new variable, not a reuse of any existing variable of the same name
  • Evaluate statements in the body of function one by one

x: 7

return 7 * 7

19 of 47

Executing a function call

def square(x):

return x * x

square(3 + 4)

square(3 + 4)

square(7)

19

Function definition

Function call

  • Evaluate argument(s) at call site - place where we are calling function from in program
  • Assign argument’s value to the formal parameter name
  • A new variable, not a reuse of any existing variable of the same name
  • Evaluate statements in the body of function one by one
  • At return statement:
  • Formal parameter variable disappears - exists only during the call
  • Call expression evaluates to “returned” value

x: 7

return 7 * 7

square(3 + 4) = 49

20 of 47

Function definitions and calls

def dbl_plus(x):

return 2 * x + 1

def instructor_name():

return “Hannah Cheung”

def calc_grade(points):

grade = points * 10

return grade

20

What are the

  • function names?
  • function body?
  • inputs or parameters?
  • arguments or parameters for each function call?

21 of 47

Function definitions and calls

def dbl_plus(x):

return 2 * x + 1

def instructor_name():

return “Hannah Cheung”

def calc_grade(points):

grade = points * 10

return grade

# main program

dbp3 = dbl_plus(3)

dbp4 = dbl_plus(4)

print(dbp3 + db4)

print(instructor_name())

my_grade = calc_grade(dbp3)

21

What are the

  • function definitions?
  • inputs or parameters?

  • function calls or “function invocations” or “call sites”?
  • arguments or parameters for each function call?

22 of 47

Function definitions and calls

def calc_grade(points):

grade = points * 10

return grade

def print_grade(points):

grade = points * 10

print(“Grade is:”, grade)

# main program

my_grade = calc_grade(10)

print_grade(10)

22

No return statement

Returns the value None

Executed for side effect

All in same file

23 of 47

Functions can call functions

def fahr_to_celsius(fahr):

return (fahr - 32) / 9.0 * 5

def celsius_to_fahr(celsius):

result = celsius / 5.0 * 9 + 32

return result

def print_fahr_to_celsius(fahr):

result = fahr_to_celsius(fahr)

print(result)

# main program

boiling = fahr_to_celsius(212)

cold = celsius_to_fahr(-30)

print(print_fahr_to_celsius(32))

23

No return statement

Returns the value None

Executed for side effect

All in same file

24 of 47

Warmup #1 - What does this print?

def celsius_to_fahr(celsius):

print(celsius / 5.0 * 9 + 32)

print(celsius_to_fahr(20))

24

25 of 47

Warmup #1 - What does this print?

def celsius_to_fahr(celsius):

print(celsius / 5.0 * 9 + 32)

return None

print(celsius_to_fahr(20))

25

26 of 47

Warmup #2 - What does this print?

def my_func(n):

total = 0

for i in range(n):

total = total + i

return total

print(my_func(4))

26

27 of 47

Warmup #3 - What does this print?

def c_to_f(c):

print(“c_to_f”)

return c / 5.0 * 9 + 32

def make_message(temp):

print(“make_message”)

return “The temperature is “ + str(temp)

for tempc in [-40, 0, 37]:

tempf = c_to_f(tempc)

message = make_message(tempf)

print(message)

27

28 of 47

Digression: Two types of output

  • An expression evaluates to a value, which can be used by the containing expression/statement
  • print statement writes text to the screen
  • Python interpreter reads statements and expressions and executes them like a calculator
    • Executing an expression prints its value
  • In a program (Visual Studio Code, Python Tutor), evaluating an expression does not print it
    • Printing an expression does not permit it to be used elsewhere

28

29 of 47

Looking up variables

  • Idea: Find the nearest variable of the given name
    • Check whether variable is defined in local scope
    • Check whether variable is defined in intermediate scope
      • not covered in CSE 160
    • Check whether variable is defined in global scope
  • If local and global variable have the same name, global variable is inaccessible (“shadowed” or “masked”)
    • Try to avoid shadowing

29

30 of 47

Looking up variables

  • Idea: Find the nearest variable of the given name
    • Check whether variable is defined in local scope
    • Check whether variable is defined in global scope

x = 22

stored = 100

def lookup():

x = 42

return stored + x

val = lookup()

x = 5

stored = 200

val = lookup()

30

31 of 47

Looking up variables: masking

  • Idea: Find the nearest variable of the given name
    • Check whether variable is defined in local scope
    • Check whether variable is defined in global scope

x = 22

stored = 100

def lookup():

x = 42

return stored + x

val = lookup()

x = 5

stored = 200

val = lookup()

x = 22

stored = 100

def lookup():

x = 42

stored = stored + x

return stored

val = lookup()

x = 5

stored = 200

val = lookup()

31

32 of 47

Temporary variables

def store_it(arg):

stored = arg

return stored

stored = 0

y = store_it(22)

print(y)

print(stored)

32

33 of 47

How many x variables?

def square(x):

return x * x

def abs(x):

if x < 0:

return -x

else:

return x

# main program

x = 42

sq3 = square(3)

print(x)

x = -22

result = abs(x)

print(result)

33

All in same file

34 of 47

Local and global scope

myvar = 1

def outer():

myvar = 1000

temp = inner()

return temp

def inner():

return myvar

print(outer())

34

35 of 47

Designing functions

  • Breaking down a program into functions is the fundamental activity of programming
  • When to use/define a function
    • DRY (Don’t Repeat Yourself)
    • Whenever you feel tempted to copy and paste code, don’t!

35

36 of 47

Variables should represent one thing

# Legal, but confusing: don’t do this!

x = 3

x = “hello”

x = [3, 1, 4, 1, 5]

36

Each variable should contain values of only one type

37 of 47

Designing functions

  1. Write the program as if the function already exists

# Main program

tempf = 32

print(“Temp in Fahr:”, tempf)

tempc = fahr_to_celsius(tempf)

print(“Temp in Celsius”, tempc)

37

38 of 47

Designing functions

  • Write the program as if the function already exists
  • Write a specification: describe the inputs and output, including their types

# Main program

tempf = 32

print(“Temp in Fahr:”, tempf)

tempc = fahr_to_celsius(tempf)

print(“Temp in Celsius”, tempc)

def fahr_to_celsius(fahr):

“““

Input: Number of degrees Fahrenheit

Return: Number of degrees Celsius

”””

38

39 of 47

Designing functions

  • Write the program as if the function already exists
  • Write a specification: describe the inputs and output, including their types
  • Write tests: example inputs and outputs

# Main program

tempf = 32

print(“Temp in Fahr:”, tempf)

tempc = fahr_to_celsius(tempf)

print(“Temp in Celsius”, tempc)

def fahr_to_celsius(fahr):

“““

Input: Number of degrees Fahrenheit

Return: Number of degrees Celsius

”””

assert fahr_to_celsius(32) == 0

assert fahr_to_celsius(212) == 100

assert fahr_to_celsius(98.6) == 37

assert fahr_to_celsius(-40) == -40

39

40 of 47

Designing functions

  • Write the program as if the function already exists
  • Write a specification: describe the inputs and output, including their types
  • Write tests: example inputs and outputs
  • Write the function body (implementation)
  • Write your plan in English (pseudocode), then translate to Python

# Main program

tempf = 32

print(“Temp in Fahr:”, tempf)

tempc = fahr_to_celsius(tempf)

print(“Temp in Celsius”, tempc)

def fahr_to_celsius(fahr):

“““

Input: Number of degrees Fahrenheit

Return: Number of degrees Celsius

”””

return (fahr - 32) / 9.0 * 5

assert fahr_to_celsius(32) == 0

assert fahr_to_celsius(212) == 100

assert fahr_to_celsius(98.6) == 37

assert fahr_to_celsius(-40) == -40

40

41 of 47

Documentation

42 of 47

Functions are an abstraction

  • Abstraction = ignore some details
  • Generalization = become usable in more contexts
  • As long as the user knows what the function means, you don’t care how it computes that value
    • You don’t care about the implementation (function body)

42

43 of 47

Types of documentation

  1. Documentation for users/clients/callers
  2. Often called the “docstring”
  3. Tells what function does
  4. Purpose, meaning, or abstraction of what it represents
  5. Parameters, behavior, what is returned/side effects

def square(x):

“““

Returns the square of its argument x.

”””

# Uses “x * x” instead of “x ** 2”

return x * x

43

for users - string as first element of function body

44 of 47

Types of documentation

  • Documentation for users/clients/callers
  • Often called the “docstring”
  • Tells what function does
  • Purpose, meaning, or abstraction of what it represents
  • Parameters, behavior, what is returned/side effects

  • Documentation for programmers who are reading code
  • Often called “comments”
  • Tells how function does it
  • Only necessary for tricky or interesting bits of code

def square(x):

“““

Returns the square of its argument x.

”””

# Uses “x * x” instead of “x ** 2”

return x * x

44

for users - string as first element of function body

for programmers - text after #

45 of 47

Multi-line strings

  • Single-quote strings
  • Examples: “hello” or ‘hello’
  • Use in program when manipulating strings, printing

  • Triple-quote strings
  • Use this version for docstrings and file description header
  • String can span multiple lines
  • Can include quotation marks
  • Example:

“““

Hello

world

”””

45

46 of 47

Comments to not write

  • Comments should give information that is not apparent from the code
  • Here is a counter-productive comment that clutters the code, which makes the code harder to read:

# increment value of x

x = x + 1

46

47 of 47

Where to write comments

  • By convention, write a comment above the code that it describes
    • Reasoning: Reader sees English explanation for the possibly-confusing code

  • May appear anywhere in program, including at end of line

  • For a comment, indentation should be consistent with surrounding code

# increment value of x

x = x + 1

x = x + 1 # increment value of x

47