Defining Your Own Functions


The keyword def is used to define a function. This example shows a function named factorial that returns the factorial of an integer. It sends the value 5 to the function and returns the value of fact.

 def factorial(n):     fact=1     for num in range(1, n+1):         fact *= num     return fact print "5 factorial is", factorial(5)

Python also allows you to define small functions called lambdas that can be passed as arguments. For example, you could use the map function to apply a lambda expression to each element in a list. You can learn how to use lambda and map in sections 4 and 5 of the Python Tutorial at http://docs.python.org/tut/tut.html.

Variable Scope

Variables in the main body of your code (outside of functions) are global. Global variables can be accessed from any part of the code, including inside a function. While this may seem convenient, it can cause some serious problems. For example, if you happen to use the same variable name for a global variable and for a variable inside a function, you could accidentally change the value of the global variable when you call the function. In fact, it’s best to avoid using global variables as much as possible. One easy way to do this is to put all of your code in functions, including the main body of code. You can then include a single line to call the main function, like this:

 #!/usr/bin/python # # wordcount.py : count the words in the filename arguments # import fileinput, re def sortkeys(dict) :     keylist=dict.keys()     keylist.sort()     return keylist def printwords (wordfreq, totalwords) :     for word in sortkeys(wordfreq) :         print "%d %s" % (wordfreq[word], word)     print "%d total words found." % totalwords def countwords(splitline, wordfreq, totalwords) :     for word in splitline :         if not wordfreq.has_key(word) :             wordfreq[word]=1         else :             wordfreq[word] += 1         totalwords += 1 def main() :     (wordfreq, totalwords)=( {}, 0)     for line in fileinput.input() :         splitline=re.findall (r"\w+", line.lower())         countwords(splitline, wordfreq, totalwords)     printwords (wordfreq, totalwords) main()

This program uses a dictionary (wordfreq) to count the frequency of each word in the input. The words are saved as keys in the dictionary, where the number of times the words appear are the values. It two methods from modules you haven’t seen yet: fileinput.input() allows you to iterate through the lines in the input, and the function re.findall() is used to divide each line into a list of lowercase words. You will learn how to use these functions in the next two sections.

Notice that even though this program is relatively short, it has been broken into four separate functions. The functions make it easier to quickly understand what each part of the program does. For example, just by reading the code in main(), you can see that the program iterates through input, splits lines, counts words, and prints some output. Even without reading the other sections-and without knowing exactly how fileinput.input() and re.findall() work-you would be able to make a pretty good guess about what the program was for.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net