DOC PREVIEW
Berkeley COMPSCI 61A - Lecture 3

This preview shows page 1 out of 4 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 4 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 4 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

61A Lecture 3Wednesday, August 31Lightning Review: Expressions2Primitive expressions:Call expressions:2 add 'hello'add ( 2 , 3 )Operator Operand 0 Operand 1mul(add(2, mul(4, 6)), add(3, 5))One big nested call expressionNumber Name StringLife Cycle of a User-Defined Function3Defining:Call expression:square( x ):return mul(x, x)>>> defsquare(2+2)Calling/Applying:square( x ):return mul(x, x)Def statementFormal parameterBodyReturn expression(return statement)Function createdBody storedName boundoperand: 2+2argument: 4Op's evaluatedFunction calledWhat happens?operator: squarefunction: squareSignatureIntrinsic name416New frame!Params boundBody evaluatedArgumentReturn valueCast of Characters: Environment Diagrams4Framea:b:Name2ValueBindingA name is bound to a valueA frame is a rectanglethat contains bindings5In a frame, there is at most one binding per nameFrames:Environments:An environment is a sequenceof framesSo far, environments only haveat most two frames(Friday: longer sequences)The global frameLocal frameEnvironmentmul:...x:New environmentAn Environment is a Sequence of Frames5mul:...x:Environments (Memory):An environment is a sequenceof framesLocal frameFrames link to each otherAn environment is a first frame, plus the frames that followAn environment is a first frame, plus the sequence of frames that followAn environment is a first frame, plus the environment that follows...First frameExisting environmentThe global frameExtendsAn Expression is Evaluated in an Environment6mul:...x:Environments (Memory):Local frameExpressions (Program):Expressions are Python codeReturn expressionValueThey are evaluated in an environment to yield a valueNot part of an environmentAn environment is a sequenceof framesFrames link to each otherAn environment is a first frame, plus the environment that followsThe global framesquare( 2 )Call expressionreturn mul(x, x)square(square(3))square(3)Multiple Environments in One Diagram!7mul:squarex: 3square:square(x):return mul(x, x)...mul(a,b):from operator import mul def square(x): return mul(x, x)square(square(3))squarex: 9981Every call to auser-defined functioncreates a newlocal frameNames Have No Meaning Without Environments8mul:square:square(x):return mul(x, x)square(-2)...mul(a,b):from operator import mul def square(x): return mul(x, x)square(-2)squareA name evaluates to the value bound to that name...in the earliest frame of the current environment...in which that name is foundsquarereturn mul(x, x)x: -2mulxFormal Parameters9def square(x): return mul(x, x)def square(y): return mul(y, y)square(-2)4return mul(__,__)vsFormal parameter names stay local to their framefrom operator import mul def square(__): return mul(__, __)square(-2)square__: -2Local framereturn mul(__, __)square:square(__):...mul:mul(a,b):Shadowing Names10def square(mul): return mul(mul, mul)square(-2)squaresquare(-2)mul: -2square:square(mul):return mul(mul, mul)return mul(mul,mul)...mul:mul(a,b):If we use this formal parameterEvaluating this call expression will failCareful!Python Feature Demonstration<Demo>OperatorsMultiple Return ValuesDocstringsDoctestsDefault ArgumentsStatements</Demo>11 <header>: <statement> <statement> ... <separating header>: <statement> <statement> ... ...Compound statements:Statements12A statementis executed by the interpretto perform an actionStatementSuiteClauseThe first header determines a statement’s typeThe header of a clause “controls” the suite that followsdef statements are compound statementsCompound Statements13Compound statements: <header>: <statement> <statement> ... <separating header>: <statement> <statement> ... ...Execution Rule for a sequence of statements:• Execute the first• Unless directed otherwise, execute the restSuiteA suite is a sequence of statementsTo “execute” a suite means to execute its sequence of statements, in orderLocal Assignment def percent_difference(x, y): difference = abs(x-y) return 100 * difference / xpercent_difference(40, 50)14percent_difference:...percent_difference(x, y):...percent_differencex:40y:50difference:10Assignment binds names in the first frame of the current environmentConditional StatementsExecution rule for conditional statements:15def absolute_value(x): """Return the absolute value of x.""" if x > 0: return x elif x == 0: return 0 else: return -x1 statement,3 clauses,3 headers,3 suitesEach clause is considered in order.1. Evaluate the header's expression.2. If it is a true value, execute the suite & skip the rest.Boolean Contexts16def absolute_value(x): """Return the absolute value of x.""" if x > 0: return x elif x == 0: return 0 else: return -xGeorge BooleBoolean Contexts17def absolute_value(x): """Return the absolute value of x.""" if x > 0: return x elif x == 0: return 0 else: return -xTwo boolean contextsFalse values in Python: False, 0, ‘’, NoneTrue values in Python: Anything else (True)(more to come)George BooleRead Section 1.5.4!Iteration181. Evaluate the header’s expression.2. If it is a true value, execute the (whole) suite, then return to step 1.Execution rule for while statements:i, total = 0, 0while i < 3: i = i + 1 total = total + ii:total:01236pred:curr:...The Fibonacci Sequencedef fib(n): """Compute the nth Fibonacci number, for n >= 2.""" pred, curr = 0, 1 # First two Fibonacci numbers k = 2 # Tracks which Fib number is curr while k < n: pred, curr = curr, pred + curr k = k + 1 return curr 190, 1, 1, 2, 3, 5, 8, 13, ...Project 1:


View Full Document

Berkeley COMPSCI 61A - Lecture 3

Documents in this Course
Lecture 1

Lecture 1

68 pages

Midterm

Midterm

5 pages

Midterm

Midterm

6 pages

Lecture 35

Lecture 35

250 pages

Lecture 14

Lecture 14

125 pages

Lecture 2

Lecture 2

159 pages

Lecture 6

Lecture 6

113 pages

Lecture 3

Lecture 3

162 pages

Homework

Homework

25 pages

Lecture 13

Lecture 13

117 pages

Lecture 29

Lecture 29

104 pages

Lecture 11

Lecture 11

173 pages

Lecture 7

Lecture 7

104 pages

Midterm

Midterm

6 pages

Midterm

Midterm

6 pages

Lecture 8

Lecture 8

108 pages

Lab 4

Lab 4

4 pages

Lecture 7

Lecture 7

52 pages

Lecture 20

Lecture 20

129 pages

Lecture 15

Lecture 15

132 pages

Lecture 9

Lecture 9

95 pages

Lecture 30

Lecture 30

108 pages

Lecture 17

Lecture 17

106 pages

Load more
Download Lecture 3
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture 3 and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture 3 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?