As you begin to learn programming, sooner or later you will run into the issue of rewriting code. That is one of the many reasons we teach and learn to write functions. Functions are much like the mathematical equivalent, they are machines, with some input and output. Somewhere in school you might have learned that a function f takes a value x and has an output y. Much like that we have functions in programming that can take variables or arguments and have an output of some result. The inner working of a function in math is more technical, like f(x) = 2x + 3. In a similar matter, functions in programming execute statements.
There are 4 different types of functions that we can consider:
- No variables and no return
- Variable and no return
- No variable and a return
- Variable and return
Let us look at some examples. First let us look at the syntax requirements by Python. Like before, we will consider Python 2.7 to be our standard. The same ideas will apply to other versions and even other languages. You can take a look at the Python 2.7 function definition for more reading, but the basic definition of a function in python will look something like this:
def <function_name>(<Variables>) : <body>
Where <function_name> is a must, <Variables> are optional and <body> can be as minimal as pass. So what is our most minimal function? The useless function:
def useless(): pass
As you may guess, using this function is pointless, but that brings up another question, how do we use functions? That is simple, we call functions, by name. So if we were to make use of this function we can call it by the statement:
Now this is pointless, since nothing will let you know that the function even executed correctly. Computers today are so fast, in a blink of an eye your program will run through the code, and without any output, there is nothing to make the user verify that something actually happened. This brings us to the first kind of functions, functions without variables and without a return. You may think this is pointless by itself, but let’s say you need to do a menu to allow the user to select from 3 options, something that looks like this:
The beginning code can look something like this:
print "1. do something" print "2. do something else" print "3. quit" user_input = raw_input("Please make a valid selection: ") if user_input == "1": print "doing something..." elif user_input == "2": print "doing something else" elif user_input == "3": quit() else: print "not a valid selection"
Now this is nice, but what if we have to repeat this, won’t it be easier in a loop. Sure it will! To change it we will need to add a while statement and set user_input to some initial value. Our code will look now like this:
user_input = 1 while user_input != 3: print "1. do something" print "2. do something else" print "3. quit" user_input = raw_input("Please make a valid selection: ") if user_input == "1": print "doing something..." elif user_input == "2": print "doing something else" elif user_input == "3": quit() else: print "not a valid selection"
Now that is a little more intuitive. Now our program will execute code, but keep going back to the main loop. It would be helpful if instead of the print statements, we change it to have a single function call, to out function that takes no variables and has no return. That is right, a useless function is perfect for printing out information.
def print_menu(): print "1. do something" print "2. do something else" print "3. quit"
You may some other usage for a function of such. I normally use them for printing out user information, such as help instructions and menus. You might find other use to them, such as updating global variables, but that is beyond the scope of this post. Let us look at our code now inside the while loop:
print_menu() user_input = raw_input("Please make a valid selection: ") if user_input == "1": print "doing something..." elif user_input == "2": print "doing something else" elif user_input == "3": quit() else: print "not a valid selection"
The next type of functions we want to examine are those who take a variable and return now value. Let’s say we want a function that will print out “ho” a given number of times. a function like that might look like this:
def ho(n): for i in range(n): print "ho", print
Notice that the function is named ho, and that it has a variable name in the parentheses. The variable will receive a value when we call the function. If no value is given, we will get a trace back that looks like this:
We want to try to avoid that. To do so, we can assign a defualt value, just in case we “forget” to give it a value. We do this by adding an equal sign and a value. Like this:
def ho(n=3): for i in range(n): print "ho", print
So now we can call this function by ethier just the name, or by giving it a number of time to print “ho”. Like this:
The output will be:
These types of functions are useful for all sort of things. usually, things that can be computed or executed without any of the results needing to come back to our main program. Let us look at another example that has more than 1 variable, the power function. Let us say that the default value of the power is always 2, but the base has to be given by the user. The result does not need to be stored, it can be printed out to the screen. This function might look like this:
def power(base,exp=2): print base ** exp
Notice that we have multiple variables, 1 with no default value and 1 with a default value. In theory, a function can has as many variables as you need. It may also have a dynamic number of variables. As a rule of thumb, if you have over 4-5 variables as arguments for your function, you may want to rethink your logic a little. Let us look at the output of our power function and some function calls:
power(2) power(5) power(5,3)
You may think that this is it, but it is not. Until now we say functions that do something and output to the screen something. What if we actually need the value? What if we are within a bigger program and we need the value of the power function? We will get back to that in a minute. Let us first talk about function with no variables. Such function are getters of values, something like a random number generator. Lets say we need a function that will return 2 every time it is called. I know, it seems pointless, but it is for demonstration only. That function will look like this:
def rtn_2(): return 2
Notice that we use a special reserved keyword return. The values, or variables, after that word is what the function returns. In this case we return the value 2. Now, our function call is the same, but since we return a value, that normally means we want to store it somewhere. So out function call changes from just the name of a function to a variable assignment statements that looks like this:
value = rtn_2()
The value returned from the function rtn_2 will be stored in the variable value for future usage. We can also have multiple return statements and multiple values returns, but that is another topic by itself. Now we are ready to talk about the most common and most useful function type, functions with variables and return types. Let us say that we want to modify our power function from before to return the value, we can modify it to look something like this:
def power2(base,exp=2): return base ** exp
That was easy. Now the value computed will be returned tot he calling function for future reference. Cool. Lets see if we can combine all 4 functions to be call from our menu program (Again, just inside the while loop):
print_menu() user_input = raw_input("Please make a valid selection: ") print if user_input == "1": n = input("enter a number: ") ho(n) elif user_input == "2": base = input("enter a number: ") print str(base) + " to the power of 2 is ", power(base) base = input("enter a number: ") exp = input("enter a number: ") print str(base) + " to the power of " + str(exp) + " is ", power(base,exp) elif user_input == "3": value = rtn_2() print "The value is " + str(value) elif user_input == "4": base = input("enter a number: ") res = power2(base) print str(base) + " to the power of 2 is " + str(res) base = input("enter a number: ") exp = input("enter a number: ") res = power2(base,exp) print str(base) + " to the power of " + str(exp) +" is " + str(res) elif user_input == "5": quit() else: print "not a valid selection" print
The full python function example can be viewed here. Some notes about the program and functions in general:
- First, you will notice some print statements, those were added for ease of use.
- Second, the function we discussed here are mostly integer ones. That is not the only case for use of functions, variable can be of any Python data type.
- Return type of function can be of any type. The ones we showed here are not the only one.
- There is much more to say about functions, but I might leave that out for next time, this article is getting long enough as is.
So there you have it, a nice beginner introduction into the wonderful world of functions. As I mentioned not 2 lines ago, there are many others function techniques and things you can do with them. I might try to have a following post covering these aspect coming out soon.