Lecture 2 – Names

Names

from operator import add, mul
from operator import *

Though you can import everything from math, or operator, it’s more common to specify. Thus,

from math import pi, sin, cos

Binding two names at once

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

We can bind the build-in function names to values

>>> max(3, 4)
4
>>> max = 7
>>> max(4, 5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

How to get “max” back?

__builtins__.max(3, 4)
max = __builtins__.max

OR

del max

f is max, g id min, max is min

Types of Expressions

Primitive expressions

Expression Type
2 number/numeral
'hello' string
add name

Call expressions

Environment Diagrams

Frames

  • Within a frame, a name CANNOT be repeated
  • Everytime a user-defined function is called, a local frame is created.

Looking up Names in Environments

The current environment is either:

  • the global frame alone, or
  • a local frame, followed by the global frame

Defining Functions

Assignment is a simple means of abstraction, by binding names to values

Function definition is a more powerful means of abstraction, by binding names to expressions

def <name>(<formal parameters>):
    return <return expression>

Function signature indicates how many arguments a function takes.

Function body defines the computation performed when the function is applied.

Hey, kudos for making it this far! Wanted to let you know that if you liked this, you might also like tmux Cheatsheet and Shortcuts.

ABOUT THE AUTHOR RSS Feed Icon

I'm Bobby Yan, a programmer, music lover, researcher, and a third-year undergraduate student at UC Berkeley majoring in Electrical Engineering and Computer Science. I am currently doing research on robotics, planning, and systems for machine learning at RISELab. In the past, I built IB Notes, a website with useful and concise study guides and notes for IB, and Spanish Vocab Builder, an iOS app to help Spanish learners. See my résumé for more details.

If you enjoyed this article, you should follow me on Twitter or sign up to get an email whenever I write something new:

Share this article with your friends: