Ahhhhh. Now this is where things start getting really interesting. Writing various functions properly is what almost all coding concerns itself with. The main body of the code is generally pretty short, with just a few function calls that, due to the wonderful nature of functions, do whatever you want. First you should remember how you might use functions to do what you want. Currently, however, your instructional vocabulary is limited to the functions that Python has built in. Should you want to do more complex things (and everyone's first coding project is always enormously complex) you'lll want to make your own ones to accomplish subtasks.

But, enough beating about the bush, it's time to see how this might be useful, and then learn how you can use this technique to further your own ends. The general idea about a function is that it is a machine that takes in data, does something to it, and spits the data back out. This is quite similar to the functions you may have learned about in your math classes, and they should feel similar because this way of thinking about things was thought up by math geeks. The way that this is expressed in computer science land is that you have a function that takes arguments and returns a value. So, what is a function you might want to make? Well, perhaps you are making a string checker program. If so, then you might want to check whether or not a particular string conforms to a particular format. If the test for conformity was a complicated one, and you knew about functions, yopu could give your buddy the job of writing the "does it conform" function - a function that would accept a string and return either true or false - and you could write the easier code.

Functions are useful in many ways:

  • they make your code clearer by decomposing funcionality into easily recognizable subparts.
  • they make collaboration possible by allowing you to just use the other code without having to know how all of its internal bits work
  • the idea of a function that calls itself (a concept known as recursion) can be used to create expressive and easy tor read code very succinctly.1
As such, you really should make every effort to decompose repeated functionality into functions. A good rule of thumb is that if the same lines of code ever happen three times over the course of your program, then those three lines should be turned into a function. Things like this, however, are the beginnings of a dive into talking about software engineering, and this is just a how to code guide.

So, how do you work these crazy things? Well, we'll do that string-conformance-testing idea. We'll check whether or not a particular string is made up of two words, where the first word starts with 'a', and the second word starts with 'b':

def conformsToSpec(words):
        import string

        words = string.split(words)

        if len(words) != 2:
            return 0
        
        return words[0][0] == 'a' and words[1][0] == 'b'
Whoah. There is a lot of new stuff there, so if you look at that and go "what the hell is he smoking?", that is quite understandable. Let's just take it line by line: (line numbers added for ease of reference)
1: def conformsToSpec(words):
2:         import string
3: 
4:         words = string.split(words)
5: 
6:         if len(words) != 2:
7:             return 0
8:         
9:         return words[0][0] == 'a' and words[1][0] == 'b'
  1. def means "define", as in "define conformsToSpec to be a function that takes one argument and calls that argument 'words'". So this line, while unfamiliar, should not be too highly voodoo. This is the function definition or, for the more computer science inclined, the function's signature. This line tells you what the function is called and how many arguments to give it.
  2. take in the string library.
  3. take the passed in string and use the function string.split() to turn it into an array of all of the words in the string. Store the resulting array in the variable words.
  4. check the length of the word. This should feel familiar.
  5. (remember, this line is only executed if the condition in the if clause is true) return the value 0, which evaluates to false when used in an if statement.
  6. Here's what is probably the most confusing line. This line evaluates the statement just like an if clause, and then returns the truth value of the statement.
Talking about this too much might make it even more confusing, so let's just try using this in a piece of code to see how it might turn out. We'll assume that this function is defined somewhere in your file already.
strings = [ "a bouncer", "Apple bat", "apple", "a b c d", "ab", "booger alpha" ]
for str in strings:
        if conformsToSpec(str):
                print str, "is an okay string!"
        else:
                print str, "does not conform"
What do you think this code will do? Try it and find out! Because computer scientisits like to generalize, functions can of course call other functions, and can contain while()s and for()s and if()s and really almost anything that it makes sense to do.

Functions are ean enourmously general concept, but the general form for declaring one is, as shown above:

def FUNCTIONNAME(ARGUMENTS):
        INSTRUCTIONS
	return SOMETHING
This format is an almost complete description, but it is important to note that the return statement is optional and other returns may be placed in the middle of the function as shown previously. This means that some functions (such as print) don't return a value. This is okay. The english sentence that this compares to is a little bit long and tortured, but it might go a little something like this:
I would like you to create a function called FUNCTIONNAME that takes ARGUMENTS and, given those arguments, performs INSTRUCTIONS and then returns SOMETHING.
So, if you wanted to, you could make a function called convertTemperature that took in as its one argument fahrenheight, preformed the instructions celsius = (fahrenheight-32)*5/9 and then returned celsius. Written out in python, it is much more succinct:
def convertTemperature(fahrenheight):
        celsius =(fahrenheight-32)*5/9 
        return celsius
This brevity, coupled with the lack of ambiguity, is the main reason that programming languages don't use the nore "natural" english language method of writing things down. Also, for more complicated functions and conditions, the sentences have the ability to descend into meaninglessness due to their length. Initially this trick of decoding into english is useful, but you will find that over time the code way of expressing it becomes more natural in most cases.

Now that you know how to write your own functions, you're unstoppable. The Linux kernel, Microsoft Word, Mozilla, e2, and all the other programs you use on a daily basis are just programs like you now know how to make. They may use other languages, and they may use weird things like objects, but in essence, all that these programs are are sequences of instructions with ifs, fors, and defs. So go wild. Believe it or not, you know know everything you need to know to understand almost any program. Writing one yourself is where the apprenticeship aspect of coding comes in.

In the following chapters, the things I present are more of a denouement of the things that have led up to this point. They will help you when and if your project goes beyond 100 or so lines, but until that point you're unstoppable. Have fun, and revel in your newfound powers

Continue on to find out how to divide your program up into multiple files, and for some rantings and ravings about good style and good languages. Also, you might find something interesting to read.

<< | Learn to Program | >>


  1. This is mostly a geek thing that makes no sense right now and seems silly, but I promise that it is totally useful and will allow you to write your programs more succinctly with fewer bugs. Let recursion do the work for you and To iterate is human, to recurse, divine

Log in or register to write something here or to contact authors.