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
- Lists
- While Loops
- Random Library
Functions
- 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:
- It contains one parameter, ch, which represents
the character to be repeated. Parameters allow functions to
be generally applicable to many problems.
- Every function is defined using def funcName(parameters):.
Parameters can be 0 or many.
- Functions are called or invoked when they need to be
used. In main, note that we invoke the function
multiple times. Each time, we send a different argument which
tells the function what value to assign the parameter. Every
function call must have a one-to-one correspondence of arguments
to parameters
- Functions can return values. repeatChar does
not need to send any values back, so there is no return statement.
- This examples shows how functions allow reuse of code
rather than duplication of effort. Note how much easier it is to
make a change to the print statement (e.g., make it 15 repeats instead
of 10) here as opposed to in pattern.py
- 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:
- Run both programs and examine the code. Does their equivalence
make sense?
- Find examples of advantages of using functions including: reusability,
modularity, and abstraction
- Debug the error in birthdayFunc.py. How does this
relate to the idea of scope of a variable? Fix the bug
- Open sumList.py to write your first functions. You should
complete the following tasks in order (finish one and test before moving
on).
- 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
- Modify printGreeting() to address the user by name
when welcoming them. HINT: how can we use parameters/arguments to do
this?
- Write a function, sumList.py that takes in a list as a
parameter, sums the values, and returns the total accumulation to the
caller.
- 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:
- What is the central purpose of our function?
- What parameters/arguments do we need to accomplish this task (note
that the user input is done in main())?
- Do we need to return a value? If so, what?
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.
- 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
- 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.
- In coinFlip.py, we will implement a solution to the above
problem using a while loop.
- 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:
- What is the initialization of my loop condition? We cannot start
a while loop without having an answer to the question
- What is the loop condition (HINT: think of how would ask this
as in if statement)?
- How do we update the answer to the loop condition? If the body
of the loop does not update the answer, the loop never ends!
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