Lecture 13 For-Loops
Announcements for This Lecture Reading Assignments/Lab • Today: Chapters 8, 10 • A3 is due on Tomorrow § Survey is now posted • Thursday: Chapter 11 § Will be graded before exam • Prelim, 10/11 5:15 OR 7:30 • A4 after exam and break § Material up to TUESDAY § Longer time to do this one § Study guide is posted § Covers this lecture and next § Times/rooms by last name • No lab next week • Review next Wednesday § Current lab due in two weeks § Room/Time are TBA § But fair game on exam 10/4/18 For Loops 2
Example: Summing the Elements of a List def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist is a list of all numbers (either floats or ints)""" pass # Stub to be implemented Remember our approach: Outline first; then implement 10/4/18 For Loops 3
Example: Summing the Elements of a List def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist 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 10/4/18 For Loops 4
Example: Summing the Elements of a List def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist is a list of all numbers (either floats or ints)""" result = 0 result = result + thelist[0] result = result + thelist[1] … There is a return result problem here 10/4/18 For Loops 5
Working with Sequences • Sequences are potentially unbounded § Number of elements inside them 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 # of elements > # of lines of code? • We need a new control structure 10/4/18 For Loops 6
For Loops: Processing Sequences # Print contents of seq The for-loop: x = seq[0] for x in seq: print(x) print(x) x = seq[1] print(x) … • Key Concepts x = seq[len(seq)-1] § loop sequence: seq print(x) § loop variable : x § body : print(x) • Remember : § Cannot program … § Also called repetend 10/4/18 For Loops 7
For Loops: Processing Sequences • loop sequence: seq The for-loop: • loop variable : x for x in seq: • body : print(x) print(x) To execute the for-loop: 1. Check if there is a “next” element of loop sequence True seq has 2. If not, terminate execution put next more elts elt in x 3. Otherwise, put the element in the loop variable 4. Execute all of the body False print(x) 5. Repeat as long as 1 is true 10/4/18 For Loops 8
Example: Summing the Elements of a List def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist 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 10/4/18 For Loops 9
Example: Summing the Elements of a List def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist is a list of all numbers (either floats or ints)""" result = 0 • loop sequence: thelist for x in thelist: result = result + x • loop variable : x • body : result=result+x return result 10/4/18 For Loops 10
Example: Summing the Elements of a List def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist is a list of all numbers (either floats or ints)""" Accumulator result = 0 variable • loop sequence: thelist for x in thelist: result = result + x • loop variable : x • body : result=result+x return result 10/4/18 For Loops 11
For Loops and Conditionals def num_ints(thelist): """Returns: the number of ints in thelist Precondition: thelist is a list of any mix of types""" # Create a variable to hold result (start at 0) # for each element in the list… # check if it is an int # add 1 if it is # Return the variable 10/4/18 For Loops 12
For Loops and Conditionals def num_ints(thelist): """Returns: the number of ints in thelist Precondition: thelist is a list of any mix of types""" result = 0 for x in thelist: if type(x) == int: Body result = result+1 return result 10/4/18 For Loops 13
Modifying the Contents of a List def add_one(thelist): """(Procedure) Adds 1 to every element in the list Precondition: thelist is a list of all numbers (either floats or ints)""" for x in thelist: DOES NOT WORK! x = x+1 # procedure; no return 10/4/18 For Loops 14
For Loops and Call Frames def add_one(thelist): add_one(seq): """Adds 1 to every elt add_one 1 Pre: thelist is all numb.""" for x in thelist: 1 thelist id4 x = x+1 2 id4 seq id4 0 5 1 4 2 7 10/4/18 For Loops 15
For Loops and Call Frames def add_one(thelist): add_one(seq): """Adds 1 to every elt add_one 2 Pre: thelist is all numb.""" for x in thelist: 1 thelist id4 x = x+1 2 x 5 id4 seq id4 0 5 1 4 2 7 10/4/18 For Loops 16
For Loops and Call Frames Loop back def add_one(thelist): add_one(seq): to line 1 """Adds 1 to every elt add_one 1 Pre: thelist is all numb.""" for x in thelist: 1 thelist id4 x = x+1 2 x 6 id4 seq id4 Increments x in frame 0 5 Does not affect folder 1 4 2 7 10/4/18 For Loops 17
For Loops and Call Frames def add_one(thelist): add_one(seq): """Adds 1 to every elt add_one 2 Pre: thelist is all numb.""" for x in thelist: 1 thelist id4 x = x+1 2 x 4 id4 seq id4 Next element stored in x. 0 5 Previous calculation lost. 1 4 2 7 10/4/18 For Loops 18
For Loops and Call Frames Loop back def add_one(thelist): add_one(seq): to line 1 """Adds 1 to every elt add_one 1 Pre: thelist is all numb.""" for x in thelist: 1 thelist id4 x = x+1 2 x 5 id4 seq id4 0 5 1 4 2 7 10/4/18 For Loops 19
For Loops and Call Frames def add_one(thelist): add_one(seq): """Adds 1 to every elt add_one 2 Pre: thelist is all numb.""" for x in thelist: 1 thelist id4 x = x+1 2 x 7 id4 seq id4 Next element stored in x. 0 5 Previous calculation lost. 1 4 2 7 10/4/18 For Loops 20
For Loops and Call Frames Loop back def add_one(thelist): add_one(seq): to line 1 """Adds 1 to every elt add_one 1 Pre: thelist is all numb.""" for x in thelist: 1 thelist id4 x = x+1 2 x 8 id4 seq id4 0 5 1 4 2 7 10/4/18 For Loops 21
For Loops and Call Frames def add_one(thelist): add_one(seq): """Adds 1 to every elt add_one Pre: thelist is all numb.""" for x in thelist: 1 thelist id4 x = x+1 2 x 8 id4 seq id4 Loop is completed. 0 5 Nothing new put in x. 1 4 2 7 10/4/18 For Loops 22
For Loops and Call Frames def add_one(thelist): add_one(seq): """Adds 1 to every elt ERASE WHOLE FRAME Pre: thelist is all numb.""" for x in thelist: 1 x = x+1 2 id4 seq id4 No changes 0 5 1 4 to folder 2 7 10/4/18 For Loops 23
On The Other Hand def copy_add_one(thelist): """Returns: copy with 1 added to every element Precondition: thelist is a list of all numbers (either floats or ints)""" mycopy = [] # accumulator for x in thelist: Accumulator keeps x = x+1 result from being lost mycopy.append(x) # add to end of accumulator return mycopy 10/4/18 For Loops 24
How Can We Modify A List? • Never modify loop var! • Need a second sequence • This is an infinite loop: • How about the positions ? for x in thelist: thelist = [5, 2, 7, 1] thelist.append(1) thepos = [0, 1, 2, 3] for x in thepos: Try this in Python Tutor thelist[x] = thelist[x]+1 to see what happens 10/4/18 For Loops 25
How Can We Modify A List? • Never modify loop var! • Need a second sequence • This is an infinite loop: • How about the positions ? for x in thelist: thelist = [5, 2, 7, 1] thelist.append(1) thepos = [0, 1, 2, 3] for x in thepos: Try this in Python Tutor thelist[x] = thelist[x]+1 to see what happens 10/4/18 For Loops 26
This is the Motivation for Iterables • Iterables are objects id1 § Contain data like a list seq id1 0 5 § But cannot slice them 1 4 • Have list-like properties 2 7 § Can use then in a for-loop § Can convert them to lists id2 alt id2 § mylist = list(myiterable) ? • Example : Files § Use open() to create object § Makes iterable for reading 10/4/18 For Loops 27
Iterables, Lists, and For-Loops >>> file = open('sample.txt') id1 >>> list(file) seq id1 0 ['This is line 1\n', 5 1 4 'This is line 2\n'] 2 7 >>> file = open('sample.txt') >>> for line in file: … print(line) id2 alt id2 This is line one ? print adds \n This is line two in addition to one from file 10/4/18 For Loops 28
Recommend
More recommend