Wednesday, October 22, 2008

Chapter 5

At the beginning of this Chapter, we learn how to make our code into a file. I will not touch up on this because it is just like saving any other type of file. The main focus of the chapter is along the lines of try and catch. This is the reason why I had trouble because I have not dealt with this in Java yet so it was all new to me. After speaking with Dr. Piercy, I started to understand this material. If you know how to use a try and catch, then this chapter will be easy for you. For those of you who don't, try and catch is a function you can use in Java. The try portion is along the lines of a method. You want the function to "try" and execute it. The Catch portion is the area where you right an exception to the action. An example of this is trying to hook up to a database. Your code could be perfect in the "try" area but you the file you are trying to reach isn't there. The catch functions catches that the file is up and you can have it return back to you as "Cannot connect to file." This is helpful because it saves you time looking at your code trying to find out what the problem is when really, your code is fine.
With this understanding we move onto Python. If you want to write out this try catch function this is how you can go abouts.

def in_fridge ();
" " " This is the comment area where you can describe your definition" " "
try:
count = fridge(wanted_food)
except KeyError:
count = 0
return count

The problem that I was running into was when entering this data, I kept getting errors. The example above is straight out of the book. What you must do is have your try and except line up with one another while the actions inside must be indented in. This is just a structure that Python abides by. I recommend you create your own example over and over to understand the structure and the set up.
With the definition above, you see that we put a parameter which is wanted_food. Say you wanted to find how many bananas were in the fridge. All you would have to type out is:

wanted_food = "bananas"
(You are assuming that you added values to fridge earlier. For instance, fridge = {"bananas" : 3, "oranges" : 4})

No comments: