CS61A(2): Functions

This is the lecture note of CS61A - Lecture 2.

Expression

An expression describes a computation and evaluates to a value.

Function, as a generalization over all notations, can be used by all expressions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
""" 
Types of expressions:

1) primitive expressions
2) call expressions
"""

# primitive expression
2000 + 15

# call expressions
max(2, 3)
min(1, -2, 3, -4, 5)
pow(100, 2) # 10000

from operator import add, mul

mul(add(4, mul(4, 6)), add(3, 5)) # 224

Evaluation of call expression

An expression's operators and operands can also be expressions.

An expression tree is as follows:

Evaluation procedure for call expressions:

  • Evaluate the operator expression
  • Evaluate the operand subexpressions from left to right
  • Apply the operator (a function) to the operands (arguments)

Names, Assignment, and User-defined Functions

Assignment

Assignment is a simple means of abstraction: binds names to values or functions.

Examples:

1
2
3
4
5
6
7
>>> from math import pi, sin

>>> radius = 10
>>> x = sin(pi / 2) # 1.0
>>> f = max
>>> f(1, 2, 3) # max(1, 2, 3)
3

Defining Functions

A function is a sequence of code that perform a particular task and can be reused easily. Function definition is a more powerful means of abstraction.

We programmers can build our own functions.

1
2
3
4
"""Just function definition won't make the function be executed."""

def <name>(<formal parameters>):
return <return expression>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# User-defined functions
from operator import add, mul

def square(x):
"""
>>> square(21)
441
>>> square(add(2, 5))
49
>>> square(square(3))
81
"""
return mul(x, x)


def sum_squares(x, y):
"""
>>> sum_squares(3, 4)
25
>>> sum_squares(5, 12)
169
"""
return add(square(x), square(y))

Procedure of calling user-defined functions is as follows:

Modules

Functions are organized into modules, which together comprise the Python library. For example, Numpy is a library, it contains many modules, i.e. many .py files.

We programmer can define our own functions modules or libraries.

🦄 External Resource: Python Standard Library