61A Lecture 12
Monday, September 30
Announcements
- Homework 3 due Tuesday 10/1 @ 11:59pm
- Optional Hog Contest due Thursday 10/3 @ 11:59pm
- Homework 4 due Tuesday 10/8 @ 11:59pm
- Project 2 due Thursday 10/10 @ 11:59pm
- Guerrilla Section 2 this Saturday 10/5 & Sunday 10/6 10am-1pm in Soda
- Topics: Data abstraction, sequences, non-local assignment
- Meet outside Soda 306
For Statements
(Demo)
Sequence Iteration
def count(s, value): total = 0 for element in s: if element == value: total = total + 1 return total Name bound in the first frame
- f the current environment
(not a new frame)
4For Statement Execution Procedure
for <name> in <expression>: <suite> 1.Evaluate the header <expression>, which must yield an iterable value (a sequence). 2.For each element in that sequence, in order:
- A. Bind <name> to that element in the first frame of the current environment.
- B. Execute the <suite>.
Sequence Unpacking in For Statements
>>> pairs = ((1, 2), (2, 2), (2, 3), (4, 4)) >>> same_count = 0 >>> for x, y in pairs: if x == y: same_count = same_count + 1 >>> same_count 2 A sequence of fixed-length sequences A name for each element in a fixed-length sequence Each name is bound to a value, as in multiple assignment
6