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.

Save 35% off the list price* of the related book or multi-format eBook (EPUB + MOBI + PDF) with discount code ARTICLE.* See informit.com/terms

This chapter is from the book

This chapter is from the book

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

Temperatures Rising?

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>>>fahr77.0

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.089.6

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.

>>>convert(32)89.6

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.

>>>convert(10)50.0>>>convert(20)68.0>>>convert(22.5)72.5

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:

>>>def convert(fahr):cels = fahr * 1.8 + 32.0return cels

>>>

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.

>>>convert<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.

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.

Note

From within the interactive environment, you should use whatever indentations the environment creates for you. Doing otherwise may cause Python to report errors and fail to run the program.

However, when you write Python scripts in separate text files, the preferred convention is to use four spaces (and no tab characters). This is somewhat arbitrary, because almost any indentation scheme works if you hold to it consistently. But four spaces is the style preferred according to the PEP-8 standard that is observed by many Python programmers.

As much as possible, this book tries to hold to this PEP-8 standard. You can read more about this typographic standard for Python programming by searching for PEP-8 online.

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.

>>>def inch_to_cent(inches):cent = inches * 2.54return cent

>>>

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:

>>>inch_to_cent(10)25.4>>>inch_to_cent(7.5)19.05

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.

>>>def inch_to_cent(x):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.

Remember, a function must be defined before a call to that function is executed.

Interlude Python’s Use of Indentation

Syntactically, Python is fundamentally different from all the languages in the C-language family—including C++, Java, and C#—as well as other languages such as BASIC. The single biggest difference is that spacing matters, particularly indentation.

In the interactive environment, Python automatically indents statements inside a control structure, such as a def, if, or while statement block. Until you terminate that block, you should accept the indentation and not try to “fix” it.

When you learn later in this chapter to compose text files as Python scripts, you can indent any number of spaces you want, but you must do it consistently. If the first statement within a block of statements is indented four spaces, the next statement must be indented four spaces as well—no more, no less.

Note that the PEP-8 specification states that four-space indentation is the preferred standard.

A pitfall awaits you in the form of invisible tab characters. You can use tabs, but the danger is that a tab may look like four blank spaces when in fact it is only one character. And if you indent with a tab on one line and use spaces to indent on the next, Python gets confused and issues a syntax error.

If possible, then, always use either one technique or the other: a single tab or multiple blank spaces. The safest policy is to have your text editor follow the rule of replacing a tab with blank spaces.

Indentation is an area in which C++ programmers are bound to feel superior. Take the following Python function:

def convert_temp(x): cels = x * 1.8 + 32.0 return cels

In Python, you must indent this way or Python gets horribly confused. In C and C++, you are freed from spacing issues for the most part, because statement blocks and function definitions are controlled by curly braces. Here’s how you might write this function in C++:

There are similarities between these two versions—the Python and the C/C++ version—but the latter gives you a lot more freedom to space things as you choose.

float convert_temp(float x){cels = x * 1.8 + 32.0; return cels; }

With a little optimization, you can even put all the code on a single line.

float convert_temp(float x){return x * 1.8 + 32.0;}

What C and C++ programmers tend to like about this is that the compiler is largely indifferent to spacing issues—as long as some whitespace appears where needed to separate variable names and keywords. C++ will never complain because you intended three spaces rather than four, which to a C++ programmer seems fussy, if not petty.

But the Python way has its own advantages. To beginning and intermediate programmers especially, Python indentation allows you to see how “deep” you are in the program. It makes relationships between different statements more obvious. And it closely echoes the indentation of pseudocode I use throughout this book.

Once you get used to Python’s reliance on indented statements, you’ll love it. Just be careful that your text editor doesn’t let you confuse tab characters with blank spaces.