2014-03-28 + HW

posted Mar 28, 2014, 5:35 AM by Samuel Konstantinovich   [ updated Mar 28, 2014, 6:55 AM ]

Goal: Using for loops

Do Now: (we sto

Evaluate each expression on paper, THEN test on the computer. Describe to your neighbor what just happened (alternate problems) see if they agree.

1. range(2,4)+range(8,13,2)

2. x='ham and eggs'

x[x.find('and'):] #think very carefully...

3. x='ham and eggs'

x.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 below...

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 

print total


CLASSWORK ON PAPER: (2 minutes)

Convert to a for loop, compare with neighbor:

j=2

while j<23:

   print j

   j+=3


MORE EXAMPLES:


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

#we can still use indices of strings

for h in range(len(name)-1): 

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

      count+=1

print count



CLASSWORK  [ Complete as Homework]

On Monday bring a printed copy of:

methods, 

test cases,

output

(use for loops instead of while loops to practice) 

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

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

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

4. Write a function printTable(N) Print a NbyN multiplication table for 1-N using nested for loops.

Comments