Week 4, Monday: Functions, indefinite loops

vim tips and tricks

All of these are from command mode, not insert mode. Hit Esc to get to command mode before trying any of these:

functions

Just like you wouldn't write a paper with only one long paragraph, we don't write long programs with only a main() function. Breaking our programs up into functions has many benefits:

For example, the tic-tac-toe program I have shown in class contains these functions:

def main():
def createWindow(w,h):
def createBoard():
def printResults(res, win):
def getUserChoice(board, win):
def drawMark(m, i, win):
def drawBoard(board, win):
def checkgameOver(board):
def compChoice(board):

This is a relatively small program, but it still has 8-10 functions.

Here is an example we wrote a few weeks ago, to count letters, without using a function:

phrase = raw_input("phrase: ")
letter = raw_input("letter: ")

count = 0
for ch in phrase:
  if ch == letter:
    count += 1     

if count == 1:
  print("There is %d %s in that phrase." % (count, letter))
else:
  print("There are %d %s's in that phrase." % (count, letter))

Here is the same program, using a count(char, text) function and a printResults(n, letter) function:

def main():
  phrase = raw_input("phrase: ")
  letter = raw_input("letter: ")
  n = count(letter, phrase)
  printResults(n, letter)

And here are the two functions, defined:

def count(char, text):
  """count up how many of char are in text"""
  num = 0
  for ch in text:
    if ch == char:
      num += 1
  return num

def printResults(n, letter):
  """print out the results with correct grammar"""
  if n == 1:
    print("There is %d %s in that phrase" % (n, letter))
  else:
    print("There are %d %s's in that phrase" % (n, letter))

Terminology related to functions:

For example:

write a silly example function

If you were writing a program to print the lyrics to the '99 bottles of beer' song, a function would be very useful. See the pattern in the song?

n bottles of beer on the wall, n bottles of beer.
Take one down and pass it around, n-1 bottles of beer on the wall.

So, given n, we can print out any of the 90+ stanzas:

def bottles(n):
  """print song lyrics for n bottles"""
  print("%d bottles of beer on the wall," % (n))
  print("%d bottles of beer." % (n))
  print("Take one down and pass it around,")
  print("%d bottles of beer on the wall.\n" % (n-1))

your turn: start of tic-tac-toe game

Given the following main(), write the draw(board) function to print a simple 3x3 board to the screen.

def main():

  board = [" "," "," "," "," "," "," "," "," "]

  draw(board)
  location = int(raw_input("0-8: "))
  board[location] = "x"
  draw(board)
  location = int(raw_input("0-8: "))
  board[location] = "o"
  draw(board)

Here is an example run of the program:

$ python ttt.py 
 | | 
-----
 | | 
-----
 | | 
0-8: 0

x| | 
-----
 | | 
-----
 | | 
0-8: 4

x| | 
-----
 |o| 
-----
 | |