Week 6, Friday: Fruitful Functions

review

exception handling

Up until now, if we get invalid input from the user, our program usually crashes:

>>> age = int(raw_input("How old are you? "))
How old are you? pony
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'pony'

With exception handling, we can do something (besides crash) with that ValueError. Instead of automatically converting the input string to an integer, we can use python's try/except to try to convert, and handle the exception, if it occurs. Here's a simple example:

userinput = raw_input("How old are you? ")
try:
  age = int(userinput)
  print("You are %d years old!" % (age))
except ValueError:
  print("That's not an integer...")

Putting the above try/except into a while loop allows your program to keep asking until it gets valid input.

 How old are you? 5.6
 That's not an integer...
 How old are you? pony
 That's not an integer...
 How old are you? 21
 You are 21 years old!

write getInteger() and getFloat()

Imagine a main() program like this:

 def main():
   print("You are in a dimly lit computer room...")
   print("What do you want to do?")
   print("1 Start working on your CS lab")
   print("2 Go play frisbee...")
   print("3 Take a nap...")
   choice = getInteger(1,3)

Write the getInteger(low, high) that prompts the user to enter an integer, and uses a while loop plus a try/except to only accept valid input (an integer from low to high):

1 Start work on your lab
2 Go play ultimate frisbee with your friends
3 Take a nap on the CS couches

      ---> 0
      please enter an integer from 1 to 3 
      ---> 6
      please enter an integer from 1 to 3 
      ---> pony
      please enter an integer from 1 to 3 
      ---> 2

Write a similar function called getFloat() (without the low and high parameters) that asks for a float from the user.

In addition to ValueError, there are many other built-in exceptions in python.