For-Loops Announcements for This Lecture Reading Assignments/Lab - - PowerPoint PPT Presentation

for loops announcements for this lecture reading
SMART_READER_LITE
LIVE PREVIEW

For-Loops Announcements for This Lecture Reading Assignments/Lab - - PowerPoint PPT Presentation

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


slide-1
SLIDE 1

For-Loops

Lecture 13

slide-2
SLIDE 2

Announcements for This Lecture Reading

  • Today: Chapters 8, 10
  • Thursday: Chapter 11

Assignments/Lab

  • A3 is due on Tomorrow

§ Survey is now posted § Will be graded before exam

  • A4 after exam and break

§ Longer time to do this one § Covers this lecture and next

  • No lab next week

§ Current lab due in two weeks § But fair game on exam

10/4/18 For Loops 2

  • Prelim, 10/11 5:15 OR 7:30

§ Material up to TUESDAY § Study guide is posted

§ Times/rooms by last name

  • Review next Wednesday

§ Room/Time are TBA

slide-3
SLIDE 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)""" pass # Stub to be implemented

10/4/18 For Loops 3

Remember our approach: Outline first; then implement

slide-4
SLIDE 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)""" # Create a variable to hold result (start at 0) # Add each list element to variable # Return the variable

10/4/18 For Loops 4

slide-5
SLIDE 5

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] … return result

10/4/18 For Loops 5

There is a problem here

slide-6
SLIDE 6

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

slide-7
SLIDE 7

For Loops: Processing Sequences

# Print contents of seq x = seq[0] print(x) x = seq[1] print(x) … x = seq[len(seq)-1] print(x)

  • Remember:

§ Cannot program … The for-loop: for x in seq: print(x)

  • Key Concepts

§ loop sequence: seq § loop variable: x § body: print(x) § Also called repetend

10/4/18 For Loops 7

slide-8
SLIDE 8

For Loops: Processing Sequences

The for-loop:

for x in seq: print(x)

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

To execute the for-loop:

1. Check if there is a “next” element of loop sequence 2. If not, terminate execution 3. Otherwise, put the element in the loop variable 4. Execute all of the body 5. Repeat as long as 1 is true

seq has more elts put next elt in x

True False

print(x)

10/4/18 For Loops 8

slide-9
SLIDE 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)""" # Create a variable to hold result (start at 0) # Add each list element to variable # Return the variable

10/4/18 For Loops 9

slide-10
SLIDE 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)""" result = 0 for x in thelist: result = result + x return result

10/4/18 For Loops 10

  • loop sequence: thelist
  • loop variable: x
  • body: result=result+x
slide-11
SLIDE 11

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 for x in thelist: result = result + x return result

10/4/18 For Loops 11

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

Accumulator variable

slide-12
SLIDE 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""" # 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

slide-13
SLIDE 13

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: result = result+1 return result

10/4/18 For Loops 13

Body

slide-14
SLIDE 14

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: x = x+1 # procedure; no return

10/4/18 For Loops 14

DOES NOT WORK!

slide-15
SLIDE 15

For Loops and Call Frames

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

10/4/18 For Loops 15

1 2 id4 5 4 7 seq id4 add_one thelist 1 id4 1 2

slide-16
SLIDE 16

For Loops and Call Frames

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

10/4/18 For Loops 16

1 2 id4 5 4 7 seq id4 add_one thelist 2 id4 1 2 x 5

slide-17
SLIDE 17

For Loops and Call Frames

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

10/4/18 For Loops 17

1 2 id4 5 4 7 seq id4 add_one thelist 1 id4 1 2 x 6

Increments x in frame Does not affect folder Loop back to line 1

slide-18
SLIDE 18

For Loops and Call Frames

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

10/4/18 For Loops 18

1 2 id4 5 4 7 seq id4 add_one thelist 2 id4 1 2 x 4

Next element stored in x. Previous calculation lost.

slide-19
SLIDE 19

For Loops and Call Frames

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

10/4/18 For Loops 19

1 2 id4 5 4 7 seq id4 add_one thelist 1 id4 1 2 x 5

Loop back to line 1

slide-20
SLIDE 20

For Loops and Call Frames

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

10/4/18 For Loops 20

1 2 id4 5 4 7 seq id4 add_one thelist 2 id4 1 2 x 7

Next element stored in x. Previous calculation lost.

slide-21
SLIDE 21

For Loops and Call Frames

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

10/4/18 For Loops 21

1 2 id4 5 4 7 seq id4 add_one thelist 1 id4 1 2 x 8

Loop back to line 1

slide-22
SLIDE 22

For Loops and Call Frames

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

10/4/18 For Loops 22

1 2 id4 5 4 7 seq id4 add_one thelist id4 1 2 x 8

Loop is completed. Nothing new put in x.

slide-23
SLIDE 23

For Loops and Call Frames

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

10/4/18 For Loops 23

1 2 id4 5 4 7 seq id4 1 2

ERASE WHOLE FRAME

No changes to folder

slide-24
SLIDE 24

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: x = x+1 mycopy.append(x) # add to end of accumulator return mycopy

10/4/18 For Loops 24

Accumulator keeps result from being lost

slide-25
SLIDE 25

How Can We Modify A List?

  • Never modify loop var!
  • This is an infinite loop:

for x in thelist: thelist.append(1)

  • Need a second sequence
  • How about the positions?

thelist = [5, 2, 7, 1] thepos = [0, 1, 2, 3] for x in thepos: thelist[x] = thelist[x]+1

10/4/18 For Loops 25

Try this in Python Tutor to see what happens

slide-26
SLIDE 26

How Can We Modify A List?

  • Never modify loop var!
  • This is an infinite loop:

for x in thelist: thelist.append(1)

  • Need a second sequence
  • How about the positions?

thelist = [5, 2, 7, 1] thepos = [0, 1, 2, 3] for x in thepos: thelist[x] = thelist[x]+1

10/4/18 For Loops 26

Try this in Python Tutor to see what happens

slide-27
SLIDE 27

This is the Motivation for Iterables

  • Iterables are objects

§ Contain data like a list § But cannot slice them

  • Have list-like properties

§ Can use then in a for-loop § Can convert them to lists § mylist = list(myiterable)

  • Example: Files

§ Use open() to create object § Makes iterable for reading

10/4/18 For Loops 27

1 2 id1 5 4 7 seq id1 id2 alt id2

?

slide-28
SLIDE 28

Iterables, Lists, and For-Loops

>>> file = open('sample.txt') >>> list(file) ['This is line 1\n', 'This is line 2\n'] >>> file = open('sample.txt') >>> for line in file: … print(line) This is line one This is line two

10/4/18 For Loops 28

1 2 id1 5 4 7 seq id1 id2 alt id2

?

print adds \n in addition to

  • ne from file
slide-29
SLIDE 29

The Range Iterable

  • range(x)

§ Creates an iterable § Stores [0,1,…,x-1] § But not a list! § But try list(range(x))

  • range(a,b)

§ Stores [a,…,b-1]

  • range(a,b,n)

§ Stores [a,a+n,…,b-1]

  • Very versatile tool
  • Great for processing ints

total = 0 # add the squares of ints # in range 2..200 to total for x in range(2,201): total = total + x*x

10/4/18 For Loops 29

Accumulator

slide-30
SLIDE 30

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)""" size = len(thelist) for k in range(size): thelist[k] = thelist[k]+1 # procedure; no return

10/4/18 For Loops 30

WORKS!

Iterator of list positions (safe)

slide-31
SLIDE 31

Important Concept in CS: Doing Things Repeatedly

  • 1. Process each item in a sequence

§ Compute aggregate statistics for a dataset, such as the mean, median, standard deviation, etc. § Send everyone in a Facebook group an appointment time

  • 2. Perform n trials or get n samples.

§ A4: draw a triangle six times to make a hexagon § Run a protein-folding simulation for 106 time steps

  • 3. Do something an unknown

number of times

§ CUAUV team, vehicle keeps moving until reached its goal

10/4/18 For Loops 31

slide-32
SLIDE 32

Important Concept in CS: Doing Things Repeatedly

  • 1. Process each item in a sequence

§ Compute aggregate statistics for a dataset, such as the mean, median, standard deviation, etc. § Send everyone in a Facebook group an appointment time

  • 2. Perform n trials or get n samples.

§ A4: draw a triangle six times to make a hexagon § Run a protein-folding simulation for 106 time steps

  • 3. Do something an unknown

number of times

§ CUAUV team, vehicle keeps moving until reached its goal

10/4/18 For Loops 32

for x in sequence: process x for x in range(n): do next thing Cannot do this yet Impossible w/ Python for