Writing Functions in Python
Within the Python interactive development environment (IDLE), writing functions is the beginning of true programming. Explore how to write functions, including using functions to calculate formulas, getting string and numeric input, and writing formatted output.
Programming is like writing a script, creating a predetermined list of words and actions for actors to perform night after night. A Python function is not so different. From within the interactive environment, you can execute a function as often as you like, and it will execute the same predefined “script.” (The term script can also refer to an entire program.)
Within the Python interactive development environment (IDLE), writing functions is the beginning of true programming. In this chapter, I explore how to write functions, including the following:
Using functions to calculate formulas
Getting string and numeric input
Writing formatted output
I happen to live in the Northwest corner of the United States, and I have Canadian relatives. When they discuss the weather, they’re always talking Celsius. They might say, “Temperature’s all the way up to 25 degrees. Gettin’ pretty warm, eh?”
For people accustomed to the Fahrenheit scale, 25 is cold enough to freeze your proverbial hockey stick. So I have to mentally run a conversion.
fahr = cels * 1.8 + 32
If you have the Python interactive environment running, this is an easy calculation. I can convert 20 degrees in my head, but what about 25? Let’s use Python! The following statements assign a value to the name cels (a variable), use that value to assign another value to the name fahr, and then finally display what the fahr value is.
>>>cels = 25
>>>fahr = cels * 1.8 + 32
So, 25 “Canadian” degrees are 77.0 degrees on the “real” (that is, the American) temperature scale. That’s comfortably warm, isn’t it? For those living north of the border, it’s practically blistering.
Python prints the answer with a decimal point: 77.0. That’s because when the interactive environment combined my input with the floating-point value 1.8, it promoted all the data to floating-point format.
Let’s try another one. What is the Fahrenheit value of 32 degrees Celsius? Actually, there’s a faster way to do this calculation. We don’t have to use variables unless we want to do so.
>>>32 * 1.8 + 32.0
Thirty-two degrees on the Celsius scale is 89.6 Fahrenheit. For a Canadian, that’s practically burning up.
But I’d like to make this calculation even easier. What I’d really like to do is just enter a function name followed by a value to convert.
And—here is the critical part—if this function worked generally, as if it were part of Python, I could use it to convert any number from Celsius to Fahrenheit. All I’d have to do is enter a different argument.
But Python lets me create my own such function. This is what the def keyword does: define a new function. We could write it this way from within the interactive environment:
cels = fahr * 1.8 + 32.0
Notice that these statements by themselves don’t seem to do anything. Actually, they do quite a bit. They associate the symbolic name convert with something referred to as a callable in Python, that is, a function.
If you display the “value” of the function, by itself, you get a cryptic message.
<function convert at 0x1040667b8>
This message tells you that convert has been successfully associated with a function. There were no syntax errors; however, runtime errors are always possible.
Not until we execute convert do we know whether it runs without errors. But this is easy. To execute a function, just follow it with parentheses—enclosing any arguments, if any.
So, 5 degrees Celsius is actually 41.0 Fahrenheit…cool but not quite freezing.
If you enter this example as shown—using the bold font to indicate what you should type as opposed to what Python prints—and if everything goes right, then congrats, you’ve just written your first Python function!
If instead you get a syntax error, remember that you can easily edit a function by 1) moving the cursor to any line of the function and 2) pressing Enter. The entire function definition will reappear, and you can edit it by moving the cursor up and down. Finally, you can reenter it again. (To reenter, put your cursor on the end of the last line and press Enter twice.)
Before resubmitting the function definition, review the following rules:
The definition of convert is followed by parentheses and the name of an argument. This name stands in for the value to be converted. In this case, the argument name is fahr.
You must type a colon (:) at the end of the first line.
The environment then automatically indents the next lines. Use this indentation. Don’t try to modify it—at least not yet.
The return statement determines what value the function produces.
Remember that in Python all names are case-sensitive.
In the interactive environment, you terminate the function by typing an extra blank line after you’re done.
Let’s take another example. Let’s define another function and this time give it the name inch_to_cent. This function is even simpler than the convert function: it changes inches to centimeters, according to the formula 1 inch = 2.54 centimeters.
cent = inches * 2.54
As with the earlier function, entering a syntactically correct definition doesn’t immediately do anything, but it does create a callable that you can then use to perform the inches-to-centimeter conversation whenever you want.
Here’s an example:
Note that the inch_to_cent function definition uses its own variable—a local variable—named cent. Because it is local, it doesn’t affect what happens to any variable named cent outside of the function.
But the use of this variable in this case isn’t really necessary. You could define the same function more succinctly, as follows. But the effect is the same in either case.
return x * 2.54
You can conceptualize the action of a function call as follows. Each call to the inch_to_cent function passes a particular value in parentheses. This value is passed to the name x inside the function definition, and the return statement produces the output after operating on the x value passed to it.
Here’s an illustration of how this works:
Remember, a function must be defined before a call to that function is executed.