Lab 5, Warm-up

A boy and a girl wearing gym clothes and stretching their arms to one side. They are warming up.

We'll start with some simple loops to get warmed up.

In examples 1-3, predict the output of each code snippet.

Example 1: Repeating code a certain number of times

for num in range(5):
     print('cs')

Example 2a: Stepping through each number in range

for num in range(4):
     print(num)

Example 2b: Stepping backward through each number in range

for num in range(4,0,-1):
     print(num)

Example 3a: Stepping through each letter in a string

for letter in 'happy':
     print(letter)

Example 3b: Stepping backward through each letter in a string

for letter in 'happy'[::-1]:
     print(letter)

Example 4: Given the function addEmUp, predict the outcome of the two invocations below.

# accumulator (gathering stuff up inside the loop)
def addEmUp(number):
     """ What would you write here for the docstring?"""
     count = 0
     for num in range(number+1):
          count = count + num # accumulating here
     return count
>>> addEmUp(0)

>>> addEmUp(4)

OPTIONAL Example 5: Given the function counter, predict the outcome of the two invocations below.

# count letter occurrences
def counter(word,letter):
     """ What would you write here for the docstring?
     """
     count = 0
     for let in word:
          if let == letter:
              count = count + 1
     return count
>>> counter('cocoa','o')

>>> counter('cocoa','x')

OPTIONAL Example 6: Given the function search, predict the outcome of the invocations below.

def search(word,letter):      
     """

     """      
     for let in word:           
         if let == letter:               
               return True      
     return False
>>>  search('coke','k') 

>>>  search('coke','a')

>>>  search('metropolitan','m')

OPTIONAL Example 6: ooh! A nested loop! (one loop inside another)

Predict the output of the code snippet below:

for letter1 in 'yes':
    for letter2 in 'no':
        print(letter1 + letter2)

Table of Contents