Python Programming for the Absolute Beginner, 3rd Edition
As you've seen with built-in functions, you can provide a function values and get values back from them. With the len() function, for example, you provide a sequence, and the function returns its length. Your own functions can also receive and return values. This allows your functions to communicate with the rest of your program.
Introducing the Receive and Return Program
I created three functions in the program Receive and Return to show the various combinations of receiving and returning values. One function receives a value. The next function returns a value. And the last function both receives and returns a value. Take a look at Figure 6.5 to see exactly what happens as a result of the program.
Here's the code:
# Receive and Return # Demonstrates parameters and return values # Michael Dawson - 2/21/03 def display(message): print message def give_me_five(): five = 5 return five def ask_yes_no(question): """ Ask a yes or no question.""" response = None while response not in ("y", "n"): response = raw_input(question).lower() return response # main display("Here's a message for you.\n") number = give_me_five() print "Here's what I got from give_me_five():", number answer = ask_yes_no("\nPlease enter 'y' or 'n': ") print "Thanks for entering:", answer raw_input("\n\nPress the enter key to exit.")
Receiving Information through Parameters
The first function I defined, display(), receives a value and prints it. It receives a value through its parameter. Parameters are essentially variable names inside the parentheses of a function header:
def display(message):
Parameters catch the values sent to the function from a function call through its arguments. So here, when display() is called, message is assigned the value provided through the argument "Here's a message for you.\n" In the main part of the program, I call display() with
display("Here's a message for you.\n")
As a result, message gets the string "Here's a message for you.\n". Then, the function runs. message, like any parameter, exists inside the function as a variable. So, the line
print message
prints the string "Here's a message for you.\n".
Although display() has only one parameter, functions can have many. To define a function with multiple parameters, list them out, separated by commas.
TRAP | When you define a function with parameters, any call to that function must include a number of argument values that can be received by all of the parameters. Otherwise, Python will complain by generating an error. |
Returning Information through Return Values
The next function I wrote, give_me_five(), returns a value. It returns a value through (believe it or not) the return statement:
return five
When this line runs, the function passes the value of five back to the part of the program that called it, and then ends. A function always ends after it hits a return statement.
It's up to the part of the program that called a function to catch the values it returns and do something with them. Here's the main part of the program, where I called the function:
number = give_me_five() print "Here's what I got from give_me_five():", number
I set up a way to catch the return value of the function by assigning the result of the function call to number. So, when the function finishes, number gets the value of 5, which is equal to 5. The next line prints number to show that it got the return value okay.
You can pass more than one value back from a function. Just list all the values you want to return, separated by commas.
TRAP | Make sure to have enough variables to catch all the return values of a function. If you don't have the right number when you try to assign them, you'll generate an error. |
Understanding Encapsulation
You might not see the need for return values when using your own functions. Why not just use the variable five back in the main part of the program? Because you can't. five doesn't exist outside of its function give_me_five(). In fact, no variable you create in a function, including its parameters, can be directly accessed outside its function. This is a good thing and is called encapsulation. Encapsulation helps keep independent code truly separate by hiding or encapsulating the details. That's why you use parameters and return values: to communicate just the information that needs to be exchanged. Plus, you don't have to keep track of variables you create within a function in the rest of your program. As your programs get large, this is a great benefit.
Encapsulation might sound a lot like abstraction. That's because they're closely related. Encapsulation is a principal of abstraction. Abstraction saves you from worrying about the details. Encapsulation hides details from you. As an example, consider a remote control for a TV with volume up and down buttons. When you use a TV remote to change the volume, you're employing abstraction, because you don't need to know what happens inside the TV for it to work. Now suppose the TV remote has 10 volume levels. You can get to them all through the remote, but you can't directly access them. That is, you can't get a specific volume number directly. You can only press the up volume and down volume buttons to eventually get to the level you want. The actual volume number is encapsulated and not directly available to you.
HINT | Don't worry if you don't totally get the subtle difference between abstraction and encapsulation right now. They're intertwined concepts, so it can be a little tricky. Plus, you'll get to see them in action again when you learn about software objects and object-oriented programming in later Chapters 8 and 9. |
Receiving and Returning Values in the Same Function
The final function I wrote, ask_yes_no(), receives one value and returns another. It receives a question and returns a response from the user, either the character "y" or "n". The function receives the question through its parameter:
def ask_yes_no(question):
question gets the value of the argument passed to the function. In this case, it's the string, "\nPlease enter 'y' or 'n': ". The next part of the function uses this string to prompt the user for a response:
response = None while response not in ("y", "n"): response = raw_input(question).lower()
The while loop keeps asking the question until the user enters either y, Y, n, or N. The function always converts the user's entry to lowercase.
Finally, when the user has entered a valid response, the function sends a string back to the part of the program that called it with
return response
and the function ends.
In the main part of the program, the return value is assigned to answer and printed:
answer = ask_yes_no("\nPlease enter 'y' or 'n': ") print "Thanks for entering:", answer
Understanding Software Reuse
Another great thing about functions is that they can easily be reused in other programs. For example, since asking the user a yes or no question is such a common thing to do, you could grab the ask_yes_no() function and use it in another program without doing any extra coding. This type of thing is called software reuse. So writing good functions not only saves you time and energy in your current project, but can also save you effort in future ones!
It's always a waste of time to "reinvent the wheel," so software reuse, using existing software and other project elements in new projects, is a technique that business has taken to heart. Software reuse can do the following:
-
Increase company productivity. By reusing code and other elements that already exist, companies can get their projects done with less effort.
-
Improve software quality. If a company already has a tested piece of code, then it can use the code with the knowledge that it's bug-free.
-
Provide consistency across software products. By using the same user interface, for example, companies can create new software that users feel comfortable with right out of the box.
-
Improve software performance. Once a company has a good way of doing something through software, using it again not only saves the company the trouble of reinventing the wheel, but also saves it from the possibility of reinventing a less efficient wheel.
One way to reuse functions you've written is to copy them into your new program. But there is a better way. You can create your own modules and import your functions into a new program, just like you import standard Python modules (such as random) and use their functions (such as randrange()). You'll learn how to create your own modules and import reusable code you've written in Chapter 9 section "Creating Modules."
Категории