Names, Assignment, and User-Defined Functions - Fri, Aug 30

Announcements

Names

Can use pre-defined names using import statements:

from math import sin, pi
sin(pi/2)

Can also define names yourself:

radius = 10

More complicated assignment statements:

area, circ = pi * radius * radius, 2 * pi * radius

If radius is reassigned, area won't change automatically. To update area, reassign it manually:

radius = 20
area = pi * radius * radius

Can also assign pre-defined functions as user-defined functions:

f = max

Can also reassign pre-defined functions to variables to never use them again (until Python is restarted):

max = 5
max(2,3) # this will throw an error since max is now an int

User-Defined Functions

# Square x
def square(x):
    return mul(x, x)

from operator import mul
mul(2, 3) # 6
mul(3, 3) # 9

square(3) # 9
square(mul(2, 3)) # 36
square(square(2)) # 16

Environment Diagrams

Not a good use of your time, but since Denero suggested them, you can use them at tutor.cs61a.org