Creating Functions


You've already seen several built-in functions in action, including len() and range(). Well, if these aren't enough for you, Python lets you create functions of your very own. Your functions work just like the ones that come standard with the language. They go off and perform a task and then return control to your program. Creating your own functions offers you many advantages. One of the biggest is that it allows you to break up your code into manageable, bite-sized chunks. Programs that are one, long series of instructions with no logical breaks are hard to write, understand, and maintain. Programs that are made up of functions can be much easier to create and work with. Just like the functions you've already met, your new functions should do one job well.

Introducing the Instructions Program

From the screen shots of the Tic-Tac-Toe game, you can probably tell that the computer opponent has a little attitude. It comes across quite clearly in the instructions the computer gives before the game. You'll get a look at the code that produces those instructions in this next program, Instructions. The code is a little different than you might expect. That's because I created a function to display the instructions. I used that same function here in Instructions. Take a look at Figure 6.4 to see a sample run of the program.

click to expand
Figure 6.4: The instructions are displayed each time with just a single line of code— a call to a function I created.

Here's the code:

 # Instructions # Demonstrates programmer-created functions # Michael Dawson - 2/21/03 def instructions():     """ Display game instructions."""     print \     """     Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe.     This will be a showdown between your human brain and my silicon processor.     You will make your move known by entering a number, 0 - 8. The number     will correspond to the board position as illustrated:                      0 | 1 | 2                     -----------                      3 | 4 | 5                     -----------                      6 | 7 | 8     Prepare yourself, human. The ultimate battle is about to begin. \n     """ # main print "Here are the instructions to the Tic-Tac-Toe game:" instructions() print "Here they are again:" instructions() print "You probably understand the game by now." raw_input("\n\nPress the enter key to exit.") 

Defining a Function

I began the definition of my new function with a single line:

 def instructions(): 

This line tells the computer that the block of code that follows is to be used together as the function instructions(). I'm basically naming this block of statements. This means that whenever I call the function instructions() in this program, the block of code runs.

This line and its block are a function definition. They define what the function does, but don't run the function. When the computer sees the function definition, it makes a note that this function exists so it can use it later. It won't actually run the function until it sees a function call for it, later in the program.

To define a function of your own, follow my example. Start with def, followed by your function name, followed by a pair of parentheses, followed by a colon, and then your indented block of statements. To name a function, follow the basic rules for naming variables. Also, try to use a name that conveys what the function produces or does.

Documenting a Function

Functions have a special mechanism that allows you to document them with what's called a docstring (or documentation string). I created the following docstring for instructions():

     """ Display game instructions.""" 

A docstring is typically a triple-quoted string and, if you use one, must be the first line in your function. For simple functions, you can do what I did here: write a single sentence that describes what the function does. Functions work just fine without docstrings, but using them is a good idea. It gets you in the habit of commenting your code and makes you describe the function's one, well-defined job. Also, a function's docstring can pop up as interactive documentation while you type your call to it in IDLE.

Calling a Programmer-Created Function

Calling a programmer-created function works just like calling a built-in function. Use the name of the function followed by a set of parentheses. I called my new function several times, each time with the line:

 instructions() 

This tells the computer to go off and execute the function I defined earlier. So each time I call it, the computer prints the instructions to the game.

Understanding Abstraction

By writing and calling functions, you practice what's known as abstraction. Abstraction lets you think about the big picture without worrying about the details. So, in this program, I can just use the function instructions() without worrying about the details of displaying the text. All I have to do is call the function with one line of code, and it gets the job done.

You might be surprised where you find abstraction, but people use it all the time. For example, consider two employees at a fast food place. If one tells the other that he just filled a #3, and "sized it," the other employee knows that the first employee took a customer's order, went to the heat lamps, grabbed a burger, went over to the deep fryer, filled their biggest cardboard container with French fries, went to the soda fountain, grabbed their biggest cup, filled it with soda, gave it all to the customer, took the customer's money, and gave the customer change. Not only would this version be a boring conversation, but it's unnecessary. Both employees understand what it means to fill a #3 and "size it." They don't have to concern themselves with all the details because they're using abstraction.




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net