knerr cs21 notes...

back to schedule

WEEK06: indefinite (while) loops, strings as objects, random, more functions...
---------------------------------------------------------------
 W: more while loops, debugging, if time, strings as objects

ANNOUNCEMENTS:
 - quiz this Friday...functions!
 - Lab 6 due THURSDAY after break (but start it early!!)


REVIEW:

  *** this getYesOrNo function is a good example of a general
      function that you can use in many programs!

	- function is general (can be used with any y/n question)
	- returns either True or False
	- uses a while loop to keep asking until we get valid input

here's an example of how it might be used:

  if getYesOrNo("Do you want to play again?"):
    play_game()
  else:
    quit_game()

and here's one way to write it:

def getYesOrNo(question):
  """
  ask the given question, return True if they answer "yes",
  False if they answer "no", and keep trying if they give
  an invalid answer
  """
  while True:
    answer = raw_input(question + " (y/n): ")
    if answer == "y":
      return True
    elif answer == "n":
      return False
    else:
      print "\nError...please answer y or n\n"


MORE REVIEW...FUNCTIONS AND WHILE LOOPS:

 - do these on paper and let's talk about them:

  <> write a function called isPositive that, given a number,
     returns True if the number is positive (greater than 0)

  <> write a while loop that asks the user for a number from
     1-10 and keeps asking until they enter a certain value (ex: 5)

  <> write a while loop that asks the user to enter a word, and
     keeps asking until they enter the word quit

 - see /home/jk/inclass/ispositive.py, while.py, and whileword.py
   for solutions


DEBUGGING:

 - our programs are getting larger, so it's important to practice
   our debugging skills

 - see if you can fix the bugs in debug1.py and debug2.py

 - take home message:

       * read the error messages, look in your program at the
         given line or maybe the line above that

       * use good variable names

       * debug as you go!! test functions as you are writing them
         and as you add them to your program

STRINGS as objects:

 - see stringOps.py for an example of how to use the str class methods

 - type help(str) during an interactive python session to see all
   of the different string methods

 - what does the strip() method do?

 - how can you use the str methods to write a robust input function
   like getmenuoption?

$  python getmenuoption.py

What do you want to do next?
 1. Spin the Wheel
 2. Buy a Vowel
 3. Guess the Puzzle
 4. Quit, I can't stand this game anymore!

Enter your choice: hello
Hey, hello isn't a valid option.  Try again...
Enter your choice: a
Hey, a isn't a valid option.  Try again...
Enter your choice: -3
Hey, -3 isn't a valid option.  Try again...
Enter your choice: 5
Hey, 5 isn't a valid option.  Try again...
Enter your choice: 2

GetMenuOption returned: 2