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

examples:

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:

nums=[1,9,3,4,9]

total=0

for j in nums:

   total+=j


This reverses the string and puts the result in newWo:

wo='aini'

newWo=''

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

   newWo=s+newWo


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

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

count=0

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

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

      count+=1





CLASSWORK ON PAPER:

Convert to a for loop:

0.

j=2

while j<23:

   print j

   j+=3



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.



Comments