This week, Python 101 discusses how to abstract out parts of yourPython code into reusable functions, add flexibility to them by allowingthem to accept different arguments, and make them return specific values.Also included: a discussion of variable scope and functions to help youwrite your own functions. Confused? All is explained within...
Python comes with a couple of built-in functions to help you work with your own user-defined functions. And yes, I realize that that sentence didn't make all that much sense...
Perhaps an example will make it clearer. Consider the Python apply() function. The sole raison d'etre of apply() is to run another function with a set of arguments. Consequently, if I had a simple function named whoAmI(),
>>> def whoAmI(name):
... print "Your name is", name
...
>>>
the following statements would be equivalent:
>>> apply(whoAmI, ["Batman, Dark Knight"])
Your name is Batman, Dark Knight
>>> whoAmI("Batman, Dark Knight")
Your name is Batman, Dark Knight
>>>
This might seem pointless at first glance; however, apply() can come in handy if functions or function arguments are generated dynamically by your program, and you are unsure of their values.
Note that the second argument to apply() must always be a sequence - list, tuple et al - containing a list of function arguments.
The map() function runs a function on every element of a list, and places the results in another list. Consider the following function, which squares the argument passed to it.
Similar to map() is the filter() function; it runs a function on a list, and creates a subset of those items which returned true. So, if I had a function which checked whether or not a number was prime (perhaps you remember this from a previous article?) and a mixed list of prime and non-prime numbers, filter() would come in handy to separate the two.
#!/usr/bin/python
# returns 1 if prime, 0 if non-prime
def isPrime(num):
for count in range(2,num):
if num % count == 0:
return 0
break
else:
return 1
# list of numbers
numList = [4, 3, 11, 18, 200, 171, 67, 5]
# filter and print result list
print filter(isPrime, numList)
And the output is
[3, 11, 67, 5]
And that just about concludes this article. This time, you've taken a big step towards better software design, by learning how to abstract out parts of your Python code into reusable functions. You've learned how to add flexibility to your functions by allowing them to accept different arguments, and how to obtain return values from them. Finally, you've learned how Python treats variables inside and outside functions, and tried out three of the most common built-in helper functions available in Python.
In the next article, I'll be expanding on this theme by discussing Python modules, constructs which add a whole new level of reusability to this powerful programming language. See you then!