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
Now that we’ve reassigned our very useful max
function to just a number, we could get it back with:
__builtins__.max(3, 4)
max = __builtins__.max
or, more simply,
del max
Expressions
An expression describes a computation and evaluates to a value.
Primitive expressions
A primitive expression is a single evaluation step. You either look up the value of a name or take the literal value. Some examples are:
Expression | Type |
---|---|
2 |
number/numeral |
'hello' |
string |
add |
name |
Call expressions
A call expression makes one or more function calls, for example:
max(1, 2)
Environment Diagrams
Frames
- Within a frame, a name cannot be repeated
- Every time 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>
A function signature indicates how many arguments a function takes.
A function body defines the computation performed when the function is applied.
Hey, kudos for making it this far! If you've liked this, you might also like Controls.