Creating and Using Functions
To manage information properly, you need to organize the tools used to perform the required tasks. Each line of code that you create performs a specific task, and you combine these lines of code to achieve a desired result. Sometimes you need to repeat the instructions with different data, and in some cases your code becomes so long that it’s hard to keep track of what each part does. Functions serve as organization tools that keep your code neat and tidy. In addition, func- tions make it easy to reuse the instructions you’ve created as needed with different data. This section of the chapter tells you all about functions. More important, in this section you start creating your first serious applications in the same way that professional developers do.
Viewing functions as code packages
You go to your closet, open the door, and everything spills out. In fact, it’s an avalanche, and you’re lucky that you’ve survived. That bowling ball in the top shelf could have done some severe damage! However, you’re armed with storage boxes and soon you have everything in the closet in neatly organized boxes. The shoes go in one box, games in another, and old cards and let-
ters in yet another. After you’re done, you can find anything you want in the closet without fear of injury. Functions are just like that — they take messy code and place it in packages that make it easy to see what you have and understand how it works.
Commentaries abound on just what functions are and why they’re necessary, but when you boil down all that text, it comes down to a single idea: Functions provide a means of packaging code to make it easy to find and access. If you can think of functions as organizers, you find that working with them is much easier. For example, you can avoid the problem that many developers have of stuffing the wrong items in a function. All your functions will have a single pur- pose, just like those storage boxes in the closet.
Understanding code reusability
You go to your closet, take out pants and shirt, remove the labels, and put them on. At the end of the day, you take everything off and throw it in the trash. Hmmm . . . That really isn’t what most people do. Most people take the clothes off, wash them, and then put them back into the closet for reuse. Functions are reusable, too. No one wants to keep repeating the
same task; it becomes monotonous and boring. When you create a function,
you define a package of code that you can use over and over to perform the same task. All you need to do is tell the computer to perform a specific task by telling it which function to use. The computer faithfully executes each instruction in the function absolutely every time you ask it to do so.
When you work with functions, the code that needs services from the func- tion is named the caller, and it calls upon the function to perform tasks for it. Much of the information you see about functions refers to the caller. The caller must supply information to the function, and the function returns information to the caller.
At one time, computer programs didn’t include the concept of code reusabil- ity. As a result, developers had to keep reinventing the same code. It didn’t take long for someone to come up with the idea of functions, though, and the concept has evolved over the years until functions have become quite flex- ible. You can make functions do anything you want. Code reusability is a nec- essary part of applications to
- Reduce development time
- Reduce programmer error
- Increase application reliability
- Allow entire groups to benefit from the work of one programmer
- Make code easier to understand
- Improve application efficiency
In fact, functions do a whole list of things for applications in the form of reus- ability. As you work through the examples in this book, you see how reus- ability makes your life significantly easier. If not for reusability, you’d still be programming by plugging 0s and 1s into the computer by hand.
Defining a function
Creating a function doesn’t require much work. Python tends to make things fast and easy for you. The following steps show you the process of creating a function that you can later access:
- Open a Python Shell
You see the familiar Python prompt.
- Type def Hello(): and press Enter.
This step tells Python to define a function named Hello. The parenthe- ses are important because they define any requirements for using the function. (There aren’t any requirements in this case.) The colon at the end tells Python that you’re done defining the way in which people will access the function. Notice that the insertion pointer is now indented, as shown in Figure 6-1. This indentation is a reminder that you must give the function a task to perform.
Define the name of your function.
- Type print(“This is my first Python function!”) and press Enter.
You should notice two things, as shown in Figure 6-2. First, the insertion pointer is still indented because IDLE is waiting for you to provide the next step in the function. Second, Python hasn’t executed the print() function because it’s part of a function and is not in the main part of the window.
IDLE is waiting for your next instruction.
The function is now complete. You can tell because the insertion point is now to the left side, as shown in Figure 6-3. In addition, the Python prompt (>>>) has returned.
Figure 6-3: The function is complete, and IDLE waits for you to pro vide another instruction.
Even though this is a really simple function, it demonstrates the pattern you use when creating any Python function. You define a name, provide any requirements for using the function (none in this case), and provide a series of steps for using the function. A function ends when an extra line is added (you press Enter twice).
Working with functions in the Edit window is the same as working with them in the Python Shell window, except that you can save the Edit window content to disk. This example also appears with the downloadable source code as FirstFunction.py. Try loading the file into an Edit window using the same technique you use in the “Using the Edit window” section of Chapter 4.
After you define a function, you probably want to use it to perform useful work. Of course, this means knowing how to access the function. In the previ- ous section, you create a new function named Hello(). To access this func- tion, you type Hello( ) and press Enter. Figure 6-4 shows the output you see when you execute this function.
Figure 6-4: Whenever you type the func tion’s name, you get the output the function provides.
Every function you create will provide a similar pattern of usage. You type the function name, an open parenthesis, any required input, and a close parenthesis; then you press Enter. In this case, you have no input, so all you type is Hello( ). As the chapter progresses, you see other examples for which input is required.
Sending information to functions
The FirstFunction.py example is nice because you don’t have to keep typing that long string every time you want to say Hello(). However, it’s also quite limited because you can use it to say only one thing. Functions should be flexible and allow you to do more than just one thing. Otherwise, you end up writing a lot of functions that vary by the data they use rather than the functionality they provide. Using arguments helps you create func- tions that are flexible and can use a wealth of data.
The term argument doesn’t mean that you’re going to have a fight with the function; it means that you supply information to the function to use in pro- cessing a request. Perhaps a better word for it would be input, but the term input has been used for so many other purposes that developers decided to use something a bit different: argument. Although the purpose of an argu- ment might not be clear from its name, understanding what it does is rela- tively straightforward. An argument makes it possible for you to send data to the function so that the function can use it when performing a task. Using arguments makes your function more flexible.
The Hello() function is currently inflexible because it prints just one string. Adding an argument to the function can make it a lot more flexible because you can send strings to the function to say anything you want. To see how arguments work, create a new function in the Python Shell window (or open the Arguments01.py file of the downloadable source; see the Introduction for the URL). This version of Hello(), Hello2(), requires an argument:
Notice that the parentheses are no longer empty. They contain a word, Greeting, which is the argument for Hello2(). The Greeting argument is actually a variable that you can pass to print() in order to see it onscreen.
Sending required arguments
You have a new function, Hello2(). This function requires that you provide an argument to use it. At least, that’s what you’ve heard so far. Type Hello2( ) and press Enter in the Python Shell window. You see an error message, as shown in Figure 6-5, telling you that Hello2() requires an argument.
Figure 6-5: You must supply an argument or you get an error message.
Not only does Python tell you that the argument is missing, it tells you the name of the argument as well. Creating a function the way you have done so far means that you must supply an argument. Type Hello2(“This is an inter- esting function.”) and press Enter. This time, you see the expected output. However, you still don’t know whether Hello2() is flexible enough to print multiple messages. Type Hello2(“Another message…”) and press Enter. You see the expected output again, as shown in Figure 6-6, so Hello2() is indeed an improvement over Hello().
You might easily to assume that Greeting will accept only a string from the tests you have performed so far. Type Hello2(1234), press Enter, and you see 1234 as the output. Likewise, type Hello2(5 + 5) and press Enter. This time you see the result of the expression, which is 10.
Sending arguments by keyword
As your functions become more complex and the methods to use them do as well, you may want to provide a little more control over precisely how you call the function and provide arguments to it. Up until now, you have posi- tional arguments, which means that you have supplied values in the order in which they appear in the argument list for the function definition. However, Python also has a method for sending arguments by keyword. In this case, you supply the name of the argument followed by an equals sign (=) and the argument value. To see how this works, open a Python Shell window and type the following function (which is also found in the Arguments02.py file):
Notice that the print() function argument includes a list of items to print and that those items are separated by commas. In addition, the arguments are of different types. Python makes it easy to mix and match arguments in this manner.
Time to test AddIt(). Of course, you want to try the function using posi- tional arguments first, so type AddIt(2, 3) and press Enter. You see the expected output of 2 + 3 = 5. Now type AddIt(Value2 = 3, Value1 = 2) and press Enter. Again, you receive the output 2 + 3 = 5 even though the posi- tion of the arguments has been reversed.
Giving function arguments a default value
Whether you make the call using positional arguments or keyword argu- ments, the functions to this point have required that you supply a value. Sometimes a function can use default values when a common value is avail- able. Default values make the function easier to use and less likely to cause errors when a developer doesn’t provide an input. To create a default value, you simply follow the argument name with an equals sign and the default value. To see how this works, open a Python Shell window and type the fol- lowing function (which you can also find in the Arguments03.py file):
This is yet another version of the original Hello() and updated Hello2() functions, but Hello3() automatically compensates for individuals who don’t supply a value. When someone tries to call Hello3() without an argu- ment, it doesn’t raise an error. Type Hello3( ) and press Enter to see for your- self. Type Hello3(“This is a string.”) to see a normal response. Lest you think the function is now unable to use other kinds of data, type Hello3(5) and press Enter; then Hello3(2 + 7) and press Enter. Figure 6-7 shows the output from all these tests.
Supply default arguments when possi ble to make your func tions easier
Creating functions with a variable number of arguments
In most cases, you know precisely how many arguments to provide with your function. It pays to work toward this goal whenever you can because functions with a fixed number of arguments are easier to troubleshoot later. However, sometimes you simply can’t determine how many arguments the function will receive at the outset. For example, when you create a Python application that works at the command line, the user might provide no argu- ments, the maximum number of arguments (assuming there is one), or any number of arguments in between.
Fortunately, Python provides a technique for sending a variable number of arguments to a function. You simply create an argument that has an asterisk in front of it, such as *VarArgs. The usual technique is to provide a second argument that contains the number of arguments passed as an input. Here is an example (also found in the VarArgs.py file) of a function that can print a
variable number of elements. (Don’t worry too much if you don’t understand it completely now — you haven’t seen some of these techniques used before.)
This example uses something called a for loop. You meet this structure in Chapter 8. For now, all you really need to know is that it takes the arguments out of VarArgs one at a time, places the individual argument into Arg, and then prints Arg using print(). What should interest you most is seeing how a variable number of arguments can work.
After you type the function into a new Python Shell window, type Hello4(1, “A Test String.”) and press Enter. You should see the number of arguments and the test string as output — nothing too exiting there. However, now type Hello4(3, “One”, “Two”, “Three”) and press Enter. As shown in Figure 6-8, the function handles the variable number of arguments without any problem at all.
Figure 6-8: Variable argument
func tions can make your applica tions more flexible.
Returning information from functions
Functions can display data directly or they can return the data to the caller so that the caller can do something more with it. In some cases, a function dis- plays data directly as well as returns data to the caller, but it’s more common for a function to either display the data directly or to return it to the caller.
Just how functions work depends on the kind of task the function is supposed to perform. For example, a function that performs a math-related task is more likely to return the data to the caller than certain other functions.
To return data to a caller, a function needs to include the keyword return, followed by the data to return. You have no limit on what you can return to a caller. Here are some types of data that you commonly see returned by a function to a caller:
- Values: Any value is You can return numbers, such as 1 or 2.5; strings, such as “Hello There!”; or Boolean values, such as True or False.
- Variables: The content of any variable works just as well as a direct The caller receives whatever data is stored in the variable.
- Expressions: Many developers use expressions as a For exam- ple, you can simply return A + B rather than perform the calculation, place the result in a variable, and then return the variable to the caller. Using the expression is faster and accomplishes the same task.
- Results from other functions: You can actually return data from another function as part of the return of your
It’s time to see how return values work. Open a Python Shell window and type the following code (or open the ReturnValue.py file instead):
This function accepts two values as input and then returns the sum of those two values. Yes, you could probably perform this task without using a function, but this is how many functions start. To test this function, type print(“The sum of 3 + 4 is ”, DoAdd(3, 4)) and press Enter. You see the expected output shown in Figure 6-9.
Return values can make your functions even more
Comparing function output
You use functions with return values in a number of ways. For example, the previous section of this chapter shows how you can use functions to provide input for another function. You use functions to perform all sorts of tasks.
One of the ways to use functions is for comparison purposes. You can actu- ally create expressions from them that define a logical output.
To see how this might work, use the DoAdd() function from the previous section. Type print(“3 + 4 equals 2 + 5 is ”, (DoAdd(3, 4) == DoAdd(2, 5))) and press Enter. You see the truth value of the statement that 3 + 4 equals 2 + 5, as shown in Figure 6-10. The point is that functions need not provide
just one use or that you view them in just one way. Functions can make your code quite versatile and flexible.
Figure 6-10: Use your functions to perform a wide variety