
Software engineers often don't write a lot of code directly. They just design giant pieces of software, working at the structure chart level (or UML level for object-oriented programs).
The goal is to divide and conquer, to break the problem down into parts small enough that it easy to program. You also want to create reusable components that can be used in may different software applications.
We've seen functions before: In Lego Mindstorms, MY BLOCKS. In NQC, we wrote some functions using 'sub' (You wrote sub-functions for spinning around, etc.)
Python has some built-in functions that you can use. For instance, 'len' is a function that accepts a list as a parameter and returns the number of elements in the list, e.g.,
list = [1,2,3]
print len(list)
Often we use 'len' within a while loop to process a list
i=0
while i<len(list)print list[i]
i=i+1
Functions in programming are like math functions: you provide the name of the function, e.g., 'len', followed by an open parenthesis, and then some arguments (e.g., list1) and then a closed parenthesis.
The function returns a value to you. In the loop example above, the return value is part of a condition. Other times, you'll want to "catch" the return value in a variable, e.g.,
length = len(list1)
Built-in functions like 'len' can be called from any python program or the interpreter. But there are also thousands of Python functions that are not 'built-in' but are still quite useful. There are many Python libraries to use, and you can also create libraries of your own.
Within the interactive interpreter or a program file, you can import existing python code. We call this set of reusable code the 'code library' and each part of it a 'module'.
For instance, let's import the math module. From the interactive interpreter prompt, type the following:
import math
result= math.sqrt(16)
print result
The import statement says you want to use math functions. But when you import a module, like 'math', you must qualify any function calls you make to functions within the library with "math." For the above example, if you typed in just 'sqrt(16)' you'd get an error. 'math.sqrt(16)' is understandable to Python because it knows that sqrt is within the math module.
Here's a description of all the functions in the math module:
http://docs.python.org/lib/module-math.html
Let's try another module called google. Type in the following:
import google
google.setLicense("H2deIvNQFHI9ilswRXR1h1+7IqnD7Pp4")
data = google.doGoogleSearch('wolber') # or put some other search string
print data.results[0].URL
print data.results[0].title
As you can see, you can call Google from your python program. Here's the
Application Programmers Interface (API) for the Python Google commands. Check it to see what else you can do with the
google module. Also, if you want to explore with the Google API, you should get
your own key (the one above is Wolber's). Here's the URL to sign up: http://www.google.com/apis/
Besides using existing functions, you can write your own.
Here is an example of a function definition:
def square(number):
result=number*number
return result
A function is basically a list of commands. By assigning a name to a bunch of commands, we create an abstraction that can be used in a larger program.
Take, for example, computing the gpa of a student. Code to perform this operation might require several commands. But if we write a function called 'computegpa(student)' from there on out our programs can just call the function.
Parameters help make a function more flexible in that it can be called to do more things. In the computegpa example, we define a parameter 'student' so that the function will work not for a particular student, but any student. This idea of making your code as general as possible is a key in software engineering.
The caller of the function must supply the correct number of arguments in the function call. For instance, to call the 'square' function above, the caller would have to send in one parameters, e.g.,
result = square(4)
The parameters sent to a function in the function call are called the actual parameters.
A function can return a value to the calling code with the 'return' statement. For instance, somewhere within the computegpa function, there will be a statement such as:
def computegpa(student):
# code to compute the gpa
return (gpa)
The calling code often catches the return value in a variable, e.g.,
gpa = computegpa(joe)
Instructor Sample: Rewriting factorial as a function.
With functions, one can break a program into simple parts. A typical Python program will have several functions and a 'main' body of code, as below:
def func1(param1,param2):
#...def func2(param1):
#...#... more functions
# main code
#...
1. In a file mymath.py, write a function 'cube(x)' which returns the cube of the parameter x (x to the 3rd power, or x*x*x).The file's main code should call 'cube(x)' a couple of times with various parameters and print the results.
2. In mymath.py, import the math module and rewrite cube(x) so that it calls the math.pow function within it.
3. Write a function howPopular(keyword) which returns the estimated number of results returned from Google for the given keyword. Write main code that loops forever allowing a user to enter keywords and see the number of results. Once the program works, use it to see which of your favorite authors is most popular according to Google.
Hint: You'll need to look at the API Spec for Google. The data returned from the search is a SearchReturnValue. It has a part called meta which has a part called estimatedTotalResultsCount.