Lecture 12: Iteration and For-Loops
(Sections 4.2 and 10.3) CS 1110 Introduction to Computing Using Python
[E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]
http://www.cs.cornell.edu/courses/cs1110/2019sp
Lecture 12: Iteration and For-Loops (Sections 4.2 and 10.3) CS - - PowerPoint PPT Presentation
http://www.cs.cornell.edu/courses/cs1110/2019sp Lecture 12: Iteration and For-Loops (Sections 4.2 and 10.3) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White] Problem:
[E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]
http://www.cs.cornell.edu/courses/cs1110/2019sp
2
3
4
5
To execute the for-loop: 1. Check if there is a “next” element of loop sequence 2. If so:
element to loop variable
3. If not, terminate execution
grades has more elements put next element in x
True False
print(x)
6
7
8
same code same code
9
same code same code
10
11
same code same code
12
same code same code
13
14
15
16
17
for num in range(5): print(str(num)) print("Once I caught a fish alive.")
18
for num in range(1,6): print(str(num)) print("Once I caught a fish alive.") for num in range(6,11): print(str(num)) print("Then I let him go again.")
19
1 2 3 4 5 Once I caught a fish alive. 6 7 8 9 10 Then I let him go again.
20
21
Watch this in the python tutor!
22
23
24
CORRECT Actually it does not do this!
25
1 2 id4 5 4 7 grades id4 add_one the_list 1 id4 1 2
Heap Space Global Space Call Frame
26
1 2 1 2 id4 5 4 7 grades id4
Heap Space Global Space
add_one the_list 1 2 id4
Call Frame
x 5
27
1 2
Increments x in frame Does not affect folder
add_one the_list 1 2 1 id4 x 1 2 id4 5 4 7 grades id4
Heap Space Global Space
Loop back to line 1
Call Frame
5 6
28
1 2
Next element stored in x. Previous calculation lost.
add_one the_list 1 2 1 2 id4
Call Frame
x 1 2 id4 5 4 7 grades id4
Heap Space Global Space
5 6 4
29
1 2 add_one the_list 1 2 1 2 1 id4
Call Frame
x 1 2 id4 5 4 7 grades id4
Heap Space Global Space
Loop back to line 1 5 6 4 5
30
1 2
Next element stored in x. Previous calculation lost.
add_one the_list 1 2 1 2 1 id4
Call Frame
x 1 2 id4 5 4 7 grades id4
Heap Space Global Space
2
5 6 4 5 7
31
1 2 add_one the_list 1 2 1 2 1 id4
Call Frame
x 1 2 id4 5 4 7 grades id4
Heap Space Global Space
Loop back to line 1
2 1
5 6 4 5 7 8
32
1 2
Loop is completed. Nothing new put in x.
add_one the_list id4
Call Frame
x RETURN NONE 1 2 id4 5 4 7 grades id4
Heap Space Global Space
1 2 1 2 1
2 1
5 6 4 5 7 8
add_one the_list id4
Call Frame
x RETURN NONE
33
1 2 1 2 id4 5 4 7 grades id4
Heap Space Global Space
1 2 1 2 1
2 1
5 6 4 5 7 8
34
35
36
CORRECT* * Runs out of memory eventually, then probably throws an error.
37
>>> len_list = list(map(len, ['a', 'bc', 'defg’])) >>> len_list [1, 2, 4]
38