Docsity

Lecture Notes on For Loops and Range Function in CPSC 121 (Fall 2012), Study notes of Computer Science

Partial preview of the text

Download Lecture Notes on For Loops and Range Function in CPSC 121 (Fall 2012) and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • For loops
  • Range function

HW

  • HW 6 out
  • Proj 1 out

The for statement

Iteration (looping) allows us to repeat blocks of code

For example, instead of writing:

the list = ["spam", "ham", "eggs"]

print(the list[0])

print(the list[1])

print(the list[2])

We can use a for statement:

for v in the list: print(v)

  • Note we don’t need to know the length of the list here!

The “accumulator pattern”

acc = initial value # "accumulate" results in this variable for x in the list: acc = acc operation x

do something with acc

Generalizes many computations over lists

  • For example, sum, product, difference, etc.

Example

the_list = [3, 4, 5, 6] diff = 50 for x in the_list: diff = diff - x print(diff)

Q: What is the value of diff after every iteration?

Writing functions that take lists as parameters

Works the same as other parameters

def print_list(the_list): for x in the_list: print(x)

my_list = [1, 2, 3] print_list(my_list) 1 2 3 print_list(["spam", "ham", "eggs"]) spam ham eggs

  • Here the list is a regular old parameter
  • When the function is called, the list is assigned to the list object

range allows us to iterate a fixed number of times

for i in range(3): print("spam")

Q: What is printed?

range also gives access to list indexes

the list = [10, 20, 30] the length = len(the list) for i in range(the length): the list[i] = the list[i] * 2

Q: What does this do to the list?

  • Doubles each value!