Page 20 - MSDN Magazine, November 2019
P. 20

The Working Programmer TED NEWARD Python: Functions
Welcome back, Pythonistas. This will be, as many of you know, the last article in this series, but more on that later. In the previous part of this series, I examined how Python flow control works— branching, looping and exception handling—but one of the most significant ways to control (and reuse) code is with the time-hon- ored approach of bundling it into a named block of code that can be invoked repeatedly. I speak, of course, of the traditional function. (Python also supports classes, of course, but much of that should be easy to pick up once you understand the function syntax.)
Predefined Functions
First things first: Unlike many of its object-oriented contemporar- ies, Python supports (and encourages) top-level functions. In fact, you could program Python entirely in a procedural fashion, if you wanted. (This is partly why Python often gets labeled a “functional” language; more on that later.)
Python has a number of built-in functions defined as part of the core environment, such as the print function I’ve already discussed. In addition to some core math functions (abs, divmod, max, min, round and pow); some type-conversion functions that transform a variable from one type to another (bool, bin, chr, ord, float, int, hex and oct, among others); and some convenience methods to help construct various types (dict makes it easier to create dictio- nary instances, and list does the same for lists); Python also has a number of “meta” functions that operate on the language or its elements directly. The eval function, for example, takes a string containing Python and executes that code. Similarly, the compile function takes a string and transforms it into a compiled object for future execution using either eval or its cousin, exec.
Unlike many of its object-oriented contemporaries, Python supports (and encourages) top-level functions.
But possibly the most “meta” of the Python functions is the dir function, which is named after the shell command of the same name. It returns a list of the names available “inside” the passed object, or the top-level scope if no object is passed. Thus, if you
fire up the Python REPL and simply type “dir” into the prompt, Python will respond with all of the global functions and classes that are currently loaded. This is a ridiculously powerful tool that’s great to use when exploring new libraries. This reflective vision of the running environment can also be used to examine all of the globals in the module via the globals function, and later, when I start defining some functions, I can examine all of the local vari- ables in the current scope using the locals function.
Function Basics
Defining functions in Python is pretty much exactly the way it is in any other programming language: You define a block of code (properly indented; this is Python, after all) with a name, and the function can take a number of parameters and return a value, like so:
def quest():
print("You must now cut down the tallest tree in the forest...") print("With... A HERRING!!!!!")
Invoking a function is, as might be assumed from the various print examples used thus far, pretty much exactly as it is in other languages—the name, followed by parentheses enclosing any parameters, and off we go:
quest()
So far, so good. If you want the function to take parameters, you include one or more names inside the parentheses of the function definition. Any value to be returned is given using the ubiquitous “return” keyword:
def theKnightsWhoSayNi(gift): if gift == "shrubbery":
return ("You must now cut down the tallest tree" "in the forest... with... A HERRING!!!!")
else:
return "You must bring us... A SHRUBBERY!!!"
(Notice that when two string literals are adjacent to one another and parenthesized, Python will concatenate them into a single string.) In keeping with Python’s dynamically typed nature, any value can be passed for a given parameter, so it’s generally a good idea to make sure users know how to use your function correctly; in Python this is done by providing a documentation string (“doc-string”) string literal as the first non-commented line of code inside the function, like so:
def theKnightsWhoSayNi(gift):
"""In order to continue your quest for Camelot, you must bring the Knights gifts. Do not mess with these guys, for they say 'Ni' at the slightest provocation!"""
if gift == "shrubbery":
return ("You must now cut down the tallest tree" "in the forest... with... A HERRING!!!!")
else:
return "You must bring us... A SHRUBBERY!!!"
16 msdn magazine


































































































   18   19   20   21   22