CS 61A lect4
CS61A lect4
1 | def fib(n): |
Describing Functions
A function’s domain is the set of all inputs it might possibly take as arguments.
A function’s range is the set of output values it might possibly return.
A pure function’s behavior is the relationship it creates between input and output
Give each function exactly one job, but make it apply to many related situations!
Don’t repeat yourself (DRY): Implement a process just once, but execute it many times
Generalizing Over Computational Processes
Summation Example:
1 | def cube(k): return pow(k, 3) |
Functions as Return Values
Functions defined within other function bodies are bound to names in a local frame
1
2
3
4
5
6
7
8
9def make_adder(n):
"""Return a function that takes one argument k and returns k + n.
>>> add_three = make_adder(3)
>>> add_three(4)
7
"""
def adder(k):
return k + n
return adder
make_adder(3)(4)
oprater operand
Lambda Expressionssquare = lambda x: x * x
an expression: evaluates to a function
unimportant in Python but important in other languages
Lambda Expressions Versus Def Statements
Only the def statement gives the function an intrinsic name, which shows up in environment diagrams but doesn’t affect execution (unless the function is printed)
return
return statements:
A return statement completes the evaluation of a call expression and provides its value:
f(x) for user-defined function f: switch to a new environment; execute f’s body
Only one return statement is ever executed while executing the body of a functionreturn None—-End the function directly
control
difference:
1 | if __________: |
andif_(________, ________, ________)
Execution Rule for Conditional Statements:
Each clause is considered in order.
- Evaluate the header’s expression (if present).
- If it is a true value (or an else header), execute the suite & skip the remaining clauses.
Evaluation Rule for Call Expressions: - Evaluate the operator and then the operand subexpressions
- Apply the function that is the value of the operator to the arguments that are the values of the operands
Logical Operators
To evaluate the expression
- Evaluate the subexpression
. - If the result is a false value v, then the expression evaluates to v.
- Otherwise, the expression evaluates to the value of the subexpression
.
To evaluate the expressionor : - Evaluate the subexpression
. - If the result is a true value v, then the expression evaluates to v.
- Otherwise, the expression evaluates to the value of the subexpression
.
Conditional Expressions
A conditional expression has the form
Evaluation rule:
- Evaluate the
expression. - If it’s a true value, the value of the whole expression is the value of the
. - Otherwise, the value of the whole expression is the value of the
. 1
2>>> x = 0
>>> abs(1/x if x != 0 else 0)
