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! Thanks for reading :P I just want to let you know that if you enjoyed this, you might also like this post on Lecture 3 – Controls.

ABOUT THE AUTHOR RSS Feed Icon

I'm Bobby Yan, a programmer, music lover and web developer. I am currently working on IB Notes, a website with useful and concise study guides and notes for IB students. I have also built the Spanish Vocabulary Builder iOS app to help Spanish learners.

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: