Saturday, September 18, 2010

Defining Functions

Functions. What are they?

In math you know a function as f(x)=3x+3. substitute any number for x and you get a value. Typically a function is used to define something, such as the rate of change in speed of a car, or a runner. One variable is time, the other is speed. If you plug the value in for one your can get the other, as long as they follow the rules of the function created to define their motion (which for now we are assuming they do). If you wanted to write that same function in Python, and all you wanted it to do is print out the value, you could write:


>>>def function(x):
    print(4*x+2)

Now every time you want to call the function, you only have to type, say...

>>>function(3)
14

The value x in "def function(x)" replaces the x in the indented lines following the defining statement and your function runs, printing 4 * 3 + 2. But the function doesn't have to take a value.

>>def declaration():
    print("When in the Course of human events.")

Here the function just prints out what the function is. A benefit to functions is that you can modularize your program. You can break it up into it's basic functions which can then be used over and over again, not only in that program but in others as well. If you create a function that asks for a user name, you can use that in any program that requires the user to input their name.

You can also nest functions. Such as...

>>>def repeat(f):
    f()
    f()

This function takes a function name as it's input and outputs that function twice.

>>repeat(declaration)
When in the Course of human events.
When in the Course of human events.

You may have noticed when you typed repeat( ... a helpful box comes up with (f), reminding you that the function takes f as it's value. But this isn't always helpful. You could instead write a docstring, or documentation string, giving more helpful information to remind you and others what to input here. You do this by placing three double quotes before and after as shown.

>>>def repeat(f):
    """Input a function name here"""
    f()
    f()

This is what it should look like. There are many, many uses for functions in programming. We'll be using functions in most, if not all, of the posts from here on out.

No comments:

Post a Comment