Week 6, Wednesday: Fruitful Functions

review

more practice with functions

See the FUNCTIONS file for a list of functions to write. Functions are crucial to writing large programs. Practice, practice, practice!

Here's the first one:

Write an `isVowel(ch)` function that takes a single character and
returns `True` if `ch` is a vowel, `False` if it is not a vowel.

Let's make use of the str method lower(), to force everything to lowercase. If we do that, then we only need to check "aeiou":

def isVowel(ch):
  """return True if ch is a vowel, False if not"""
  vowels = list("aeiou")
  if ch.lower() in vowels:
    return True
  else:
    return False

Note: you could be clever and just do this:

def isVowel(ch):
  """return True if ch is a vowel, False if not"""
  vowels = list("aeiou")
  return ch.lower() in vowels

Why does that work?

In general, I am against being clever, if it makes your code harder for others to understand.

asking yes/no questions

Here's another common function:

Write a function called getYesOrNo(prompt) that takes a string prompt
and returns either "yes" or "no". Your function should keep asking the
question until it gets either a "yes" or a "no" (or 'y','Yes','No', etc)
from the user.

For this one, we want to loop until we get valid input. Using a while True, we can just return when we get valid input. Remember, the return statement ends the function (and the while loop).

def getYesOrNo(prompt):
  """ask yes/no question, return yes/no"""

  yeslist = ["yes","y"]
  nolist = ["no","n"]
  while True:
    answer = raw_input(prompt).lower()
    if answer in yeslist:
      return "yes"
    elif answer in nolist:
      return "no"
    else:
      print("please answer either yes or no!!")