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

lecture 11 iteration and for loops
SMART_READER_LITE
LIVE PREVIEW

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

http://www.cs.cornell.edu/courses/cs1110/2020sp Lecture 11: Iteration and For Loops (Sections 4.2 and 10.3) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Fan, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]


slide-1
SLIDE 1

Lecture 11: Iteration and For‐Loops

(Sections 4.2 and 10.3) CS 1110 Introduction to Computing Using Python

[E. Andersen, A. Bracy, D. Fan, D. Gries, L. Lee,

  • S. Marschner, C. Van Loan, W. White]

http://www.cs.cornell.edu/courses/cs1110/2020sp

slide-2
SLIDE 2
  • A1 revision: Resubmit today to get one more round of feedback.

Revision window closes Tu Mar 3.

  • Check your email settings: accept email from course (CSCMS‐noreply,

cs1110‐prof, cs1110‐staff)

  • The deadline for notifying us of prelim conflict was Wedn Feb 26. We

will allow late requests on CMS until 11:59pm Feb 27, but no promise

  • f being able to accommodate late requests.
  • Students with submitted SDS accommodation letter: must email us if

you have not received email from us about arrangements for prelim 1.

  • A2 due Fri 2/28. Submit on CMS. Can work with a partner. Remember

academic integrity!

  • Read §6.2 before next lecture

Announcements

2

No-laptop zone on your left

front

  • k
slide-3
SLIDE 3

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)"""

3

slide-4
SLIDE 4

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

4

How will we do this?

slide-5
SLIDE 5

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

5

Houston, we have a problem

slide-6
SLIDE 6

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

6

slide-7
SLIDE 7

For Loops: Processing Sequences

fo for x in grades: print(x)

  • loop sequence: grades
  • loop variable: x
  • loop 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 1)

3) If not, terminate execution

grades has more elements put next element in x

True False

print(x)

7

slide-8
SLIDE 8

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

8

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

Accumulator variable

slide-9
SLIDE 9

9

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-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? (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-12
SLIDE 12

12

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-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

14

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-15
SLIDE 15

# 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"""

15

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

slide-16
SLIDE 16

For Loop with labels

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

16

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

Loop sequence Loop variable Loop body Accumulator variable

slide-17
SLIDE 17

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? ran range to the rescue!

17

slide-18
SLIDE 18

range(x) returns 0,1,…,x‐1 Important: ran range does not return a list  need to convert range’s return value into a list range(a,b) returns a,…,b‐1

ra range: a handy counting function!

18

>>> 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-19
SLIDE 19

ra range in a for-loop, v1

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

19

1 2 3 4 Once I caught a fish alive.

slide-20
SLIDE 20

ra range in a for-loop, v2

for numin range(1,6): print(str(num)) print("Once I caught a fish alive.") for numin range(6,11): print(str(num)) print("Then I let him go again.")

20

1 2 3 4 5 Once I caught a fish alive. 6 7 8 9 10 Then I let him go again.

slide-21
SLIDE 21

What gets printed?

21

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

slide-22
SLIDE 22

Modifying the Contents of a List

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

lab_scores = [8,9,10,5,9,10] print("Initial grades are: "+str(lab_scores)) add_bonus(lab_scores) print("With bonus, grades are: "+str(lab_scores))

22

Watch this in the python tutor!

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

slide-23
SLIDE 23

Common For‐Loop Mistakes (1)

Mistake #1: Modifying the loop variable instead

  • f the list itself.

24

slide-24
SLIDE 24

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)

25

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-25
SLIDE 25

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)

26

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-26
SLIDE 26

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)

27

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

Heap Space Global Space Call Frame

slide-27
SLIDE 27

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)

28

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-28
SLIDE 28

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)

29

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-29
SLIDE 29

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)

30

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-30
SLIDE 30

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)

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 5 6 4 5

slide-31
SLIDE 31

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)

32

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-32
SLIDE 32

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)

33

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-33
SLIDE 33

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)

34

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-34
SLIDE 34

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)

35

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? 

slide-35
SLIDE 35

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.

36

slide-36
SLIDE 36

For-Loop Mistake #2 (Q)

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

37

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-37
SLIDE 37

For-Loop Mistake #2 (A)

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

38

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.