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

These lecture notes from cpsc 121 (fall 2012) cover the use of for loops and the range function in programming. The syntax of the for statement, the concept of sequence objects, and the accumulator pattern. It also demonstrates how to write functions that take lists as parameters and how to use the range function to create sequences of integers.

Typology: Study notes

2012/2013

Uploaded on 09/28/2013

noob
noob 🇮🇳

4.4

(25)

105 documents

1 / 7

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Lecture Notes CPSC 121 (Fall 2012)
Today ...
For loops
Range function
HW
HW 6 out
Proj 1 out
S. Bowers 1 of 7
pf3
pf4
pf5

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!