Lecture 31:

posted Mar 19, 2013, 6:21 AM by Samuel Konstantinovich   [ updated Mar 19, 2013, 8:19 AM ]

Goal: Using for loops

Do Now: On a new sheet of looseleaf, with your name/period on top complete the 6 problems below:

Evaluate each expression, you have 4 minutes.

1. range(23,31)

2. range(2,4)+range(8,15,2)

3. len('ham and'+'eggs')

4. 'ham and eggs'.find('a')

5. 'ham and eggs'.remove('ham') #think very carefully...

6. 'ham and eggs'.strip('has') #also think carefully...

For loops:

collection: Lists and strings are collections of data, but there are more collections in python like dictionaries that we havent learned yet.

A for loop has the format:

for variable in collection:

do something with variable

on as many lines as you want


This will print each of the 5 values one at a time:

for j in [1,2,9,8,6]:

   print j

This will print the values in the range one at a time:

for t in range(10):

print t

This calculates the sum of all the values in nums:



for j in nums:


This reverses the string and puts the result in newWo:



for s in wo: #s is one character of the string


This counts how many pairs of matching letters are adjacent to eachother.

name='doo noot askk mee four halp with yuur graamaar!!'


for h in range(len(name)-1): #we can still use indices of strings

   if name[h]==name[h+1]:



Convert to a for loop:



while j<23:

   print j


CLASSWORK ON THE COMPUTER (use for loops instead of while loops to practice)

1. Write a function that returns the mean of a list of integers (do not use the built in SUM)

2. Write a function that finds the largest value of a list of integers. (don't use built in MAX or SORT)

3. Write a function that goes through a string and shifts each charcter forward one character. A becomes B, c becomes d etc. Then returns the new string.

3. Print a 12by12 multiplication table for 1-12 using nested for loops.