Lecture 12: Iteration and For-Loops (Sections 4.2 and 10.3) CS - - PowerPoint PPT Presentation

lecture 12 iteration and for loops
SMART_READER_LITE
LIVE PREVIEW

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:


slide-1
SLIDE 1

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

slide-2
SLIDE 2

Problem: Summing the Elements of a List

def sum(the_list): """Returns: the sum of all elements in the_list Precondition: the_list is a list of all numbers (either floats or ints)"""

2

slide-3
SLIDE 3

Approach: Summing the Elements of a List

def sum(the_list): """Returns: the sum of all elements in the_list Precondition: the_list is a list of all numbers (either floats or ints)""" # Create a variable to hold result (start at 0) # Add each list element to variable # Return the variable

3

How will we do this?

slide-4
SLIDE 4

1st Attempt: Summing the Elements of a List

def sum(the_list): """Returns: the sum of all elements in the_list Precondition: the_list is a list of all numbers (either floats or ints)""" result = 0 result = result + the_list[0] result = result + the_list[1] … return result

4

Houston, we have a problem

slide-5
SLIDE 5

Working with Sequences

  • Sequences are potentially unbounded

§ Number of elements is not fixed § Functions must handle sequences of different lengths § Example: sum([1,2,3]) vs. sum([4,5,6,7,8,9,10])

  • Cannot process with fixed number of lines

§ Each line of code can handle at most one element § What if there are millions of elements?

  • We need a new approach

5

slide-6
SLIDE 6

For Loops: Processing Sequences

for x in grades: print(x)

  • loop sequence: grades
  • loop variable: x
  • body: print(x)

To execute the for-loop: 1. Check if there is a “next” element of loop sequence 2. If so:

  • assign next sequence

element to loop variable

  • Execute all of the body
  • Go back to Line 1

3. If not, terminate execution

grades has more elements put next element in x

True False

print(x)

6

slide-7
SLIDE 7

Solution: Summing the Elements of a List

def sum(the_list): """Returns: the sum of all elements in the_list Precondition: the_list is a list of all numbers (either floats or ints)""" result = 0 for x in the_list: result = result + x return result

7

  • loop sequence: the_list
  • loop variable: x
  • body: result=result+x

Accumulator variable

slide-8
SLIDE 8

8

What gets printed? (Q1)

my_list = [1] s = 0 for x in my_list: s = s + x print(s) my_list = [1,7,2] s = 0 for x in my_list: s = s + x print(s) my_list = [] s = 0 for x in my_list: s = s + x print(s)

same code same code

slide-9
SLIDE 9

9

What gets printed? (A1)

my_list = [1] s = 0 for x in my_list: s = s + x print(s) my_list = [1,7,2] s = 0 for x in my_list: s = s + x print(s) my_list = [] s = 0 for x in my_list: s = s + x print(s) 1 10

same code same code

slide-10
SLIDE 10

10

What does this loop do?

my_list = [1] s = 0 for x in my_list: s = s + x print(s) A: it sums the elements in my_list B: it prints the elements in my_list C: it counts the elements in my_list D: it adds one to the elements in my_list E: none of the above

slide-11
SLIDE 11

11

What gets printed? (Q1)

my_list = [1] c = 0 for x in my_list: c = c + 1 print(c) my_list = [1,7,2] c = 0 for x in my_list: c = c + 1 print(c) my_list = [] c = 0 for x in my_list: c = c + 1 print(c)

same code same code

slide-12
SLIDE 12

12

What gets printed? (A1)

my_list = [1] c = 0 for x in my_list: c = c + 1 print(c) my_list = [1,7,2] c = 0 for x in my_list: c = c + 1 print(c) my_list = [] c = 0 for x in my_list: c = c + 1 print(c) 1 3

same code same code

slide-13
SLIDE 13

13

What does this loop do?

my_list = [1] c = 0 for x in my_list: c = c + 1 print(c) A: it sums the elements in my_list B: it prints the elements in my_list C: it counts the elements in my_list D: it adds one to the elements in my_list E: none of the above

slide-14
SLIDE 14

# Create var. to keep track of 0's # for each element in the list… # check if it is equal to 0 # add 1 if it is # Return the variable/counter

For Loops and Conditionals

def num_zeroes(the_list): """Returns: the number of zeroes in the_list Precondition: the_list is a list"""

14

count = 0 for x in the_list: if x == 0: count = count + 1 return count

slide-15
SLIDE 15

For Loop with labels

def num_zeroes(the_list): """Returns: the number of zeroes in the_list Precondition: the_list is a list"""

15

count = 0 for x in the_list: if x == 0: count = count + 1 return count

Loop sequence Loop variable Body Accumulator variable

slide-16
SLIDE 16

What if we aren’t dealing with a list?

So far we’ve been building for-loops around elements of a list. What if we just want to do something some number of times? range to the rescue!

16

slide-17
SLIDE 17

range(x) returns 0,1,…,x-1 Important: range does not return a list à need to convert ranges’ return value into a list range(a,b) returns a,…,b-1

range: a handy counting function!

17

>>> print(range(6)) range(0, 6)

>>> second_six = list(range(6,13))

>>> print(second_six) [6, 7, 8, 9, 10, 11, 12]

>>> first_six = list(range(6)) >>> print(first_six) [0, 1, 2, 3, 4, 5]

slide-18
SLIDE 18

range in a for-loop, v1

for num in range(5): print(str(num)) print("Once I caught a fish alive.")

18

1 2 3 4 Once I caught a fish alive.

slide-19
SLIDE 19

range in a for-loop, v2

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.

slide-20
SLIDE 20

What gets printed?

20

A: 0 B: 2 C: 3 D: 4 E: 5 a = 0 for b in range(0, 4): a = a + 1 print(a)

slide-21
SLIDE 21

Modifying the Contents of a List

def inflate_grades(grades): """Adds 1 to every element in a list of grades (either floats or ints)""" size = len(grades) for k in range(size): grades[k] = grades[k]+1

lab_scores = [8,9,10,5,9,10] print("Initial grades are: "+str(lab_scores)) inflate_grades(lab_scores) print("Inflated grades are: "+str(lab_scores))

21

Watch this in the python tutor!

If you need to modify the list, you need to use range to get the indices.

slide-22
SLIDE 22

Common For-Loop Mistakes (1)

Mistake #1: Modifying the loop variable instead

  • f the list itself.

22

slide-23
SLIDE 23

For-Loop Mistake #1 (Q)

def add_one(the_list): """Adds 1 to every element in the list Precondition: the_list is a list of all numbers (either floats or ints)""" for x in the_list: x = x+1 a = [5, 4, 7] add_one(a) print(a)

23

A: [5, 4, 7] B: [5, 4, 7, 5, 4, 7] C: [6, 5, 8] D: Error E: I don’t know What gets printed?

Modifying the loop variable (here: x).

slide-24
SLIDE 24

For-Loop Mistake #1 (A)

def add_one(the_list): """Adds 1 to every element in the list Precondition: the_list is a list of all numbers (either floats or ints)""" for x in the_list: x = x+1 a = [5, 4, 7] add_one(a) print(a)

24

A: [5, 4, 7] B: [5, 4, 7, 5, 4, 7] C: [6, 5, 8] D: Error E: I don’t know What gets printed?

Modifying the loop variable (here: x).

CORRECT Actually it does not do this!

slide-25
SLIDE 25

Modifying the Loop Variable (1)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

25

1 2 id4 5 4 7 grades id4 add_one the_list 1 id4 1 2

Heap Space Global Space Call Frame

slide-26
SLIDE 26

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

Modifying the Loop Variable (2)

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

slide-27
SLIDE 27

Modifying the Loop Variable (3)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

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

slide-28
SLIDE 28

Modifying the Loop Variable (4)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

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

slide-29
SLIDE 29

Modifying the Loop Variable (5)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

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

slide-30
SLIDE 30

Modifying the Loop Variable (6)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

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

slide-31
SLIDE 31

Modifying the Loop Variable (7)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

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

slide-32
SLIDE 32

Modifying the Loop Variable (8)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

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

slide-33
SLIDE 33

add_one the_list id4

Call Frame

x RETURN NONE

Modifying the Loop Variable (9)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

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

No lasting changes. What did we accomplish? L

slide-34
SLIDE 34

Common For-Loop Mistakes (2)

Mistake #1: Modifying the loop variable instead

  • f the list itself.

Mistake #2: Modifying the loop sequence as you walk through it.

34

slide-35
SLIDE 35

For-Loop Mistake #2 (Q)

b = [1, 2, 3] for a in b: b.append(a) print b

35

A: never prints b B: [1, 2, 3, 1, 2, 3] C: [1, 2, 3] D: I do not know

Modifying the loop sequence as you walk through it. What gets printed?

slide-36
SLIDE 36

For-Loop Mistake #2 (A)

b = [1, 2, 3] for a in b: b.append(a) print b

36

A: never prints b B: [1, 2, 3, 1, 2, 3] C: [1, 2, 3] D: I do not know

Modifying the loop sequence as you walk through it. What gets printed?

CORRECT* * Runs out of memory eventually, then probably throws an error.

INFINITE LOOP!

slide-37
SLIDE 37

The Map Function

map(⟨function⟩, ⟨list⟩)

  • ⟨function⟩ takes 1 parameter
  • Otherwise, error

Important: map does not return a list à need to convert map’s return value into a list

37

map(f, [a,b,c,d]) f(a), f(b), f(c), f(d)

>>> len_list = list(map(len, ['a', 'bc', 'defg’])) >>> len_list [1, 2, 4]

slide-38
SLIDE 38

The Filter Function

filter(⟨Boolean_function⟩, ⟨list⟩)

  • ⟨function⟩ takes 1 parameter
  • ⟨function⟩ returns a Boolean
  • Collects elements of ⟨list⟩ for

which ⟨Boolean_function⟩ returns True

Important: filter does not return a list à need to convert map’s return value into a list See ints.py to see filter in action

38

filter(f, [a,b,c]) a if f(a)==True, b if f(b)==True, c if f(c)==True,