In Class: Week 4


Run update21 to download this week's files and move to our class directory:

    $ cd 
    $ update21 
    $ cd cs21/inclass/w04-functions
    $ pwd
      /home/your_user_name/cs21/inclass/w04-functions
	

Topics


Functions

  1. To get a basic understanding of functions, we will open two equivalent programs pattern.py and patternFunc.py. Both of these programs print out simple patterns. However, patternFunc.py uses a function repeatChar to define a commonly used operation. Not the following about the function:

  2. Next, we will open birthday.py and birthdayFunc.py which apply a mathematical transformation of a person's birth month, day, and year to create a special number. These programs do the same thing, except one uses functions. Answer the following questions:

  3. Open sumList.py to write your first functions. You should complete the following tasks in order (finish one and test before moving on).
    1. Write a function printGreeting() to print a welcome message to the user. Note that you should not need to make any changes to the main() function to accomplish this
    2. Modify printGreeting() to address the user by name when welcoming them. HINT: how can we use parameters/arguments to do this?
    3. Write a function, sumList.py that takes in a list as a parameter, sums the values, and returns the total accumulation to the caller.

  4. In countLetters.py, we will write a program to convert the following program into one that uses functions. You should write a function getCount() that returns the number of times letter appears in text:
    def main():
      text = raw_input("Enter text: ")
      letter = raw_input("Enter letter to count: ")
    
      #accumulate
      total = 0
      for ch in text:
        if ch == letter:
          total += 1
      print("There are %d instances of the letter %s" % (total, letter))
    main()
    		
    Before we code, answer these questions:

Lists

Lists look remarkably similar to strings with a few notable exceptions. We can use similar operations including:

Random library

To obtain random values, we need to bring in a library of functions just like we did with the math library. This can be done using from random import * or import random.
  1. In sumList.py, we will add one more function. Instead of manually creating a list in main, we will call a function getList() that will return a list of randomly create numbers from 0 to 10.
    def getList(size):
        """
        Create a list of numbers
        Parameters: size - how big the list should be
        Return: a lists of randomly generated values of length size
        """
        lst = []
    
        for i in range(size): 
          newnum = randrange(0, 10)
          lst.append(newnum)
    
        print(lst)
        return lst
    

  2. Next, on paper, work with your neighbor to think about an alternate problem. Come up with an algorithm (in words, code is not required) to flip a coin 100 times. You should count how many "heads" occur and output that to the user. What type of pattern are we using?

Indefinite loops

Think about a slightly different problem. Instead of counting the number of heads in 100 coin flips, we want to count how many flips it takes to get a total of 10 heads. How can we do this? A problem with for loops is that they require a specific number of iterations (hence the name definite). How do we do repetition if we don't know the exact count? We will use indefinite, or while loops.
  1. In coinFlip.py, we will implement a solution to the above problem using a while loop.

  2. A common usage of while loops is to validate user input (we should never assume a user knows what he/she is doing!). Let us modify birthdayFunc.py to more robustly get an integer from the user. Before coding, ask yourself these questions: Here is the solution to getInt() using a while loop. Implement it and test it out!
    def getInt(low, high):
        choice = int(raw_input("Enter number %d through %d: " % (low, high)))
        while choice < low or choice > high:
            choice = int(raw_input("Try again.  Enter number %d through %d: " % (low, high)))
    
        return choice