Introduction to Functions in Python

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.

500px-Function_machine2.svg

There are 4 different types of functions that we can consider:

  1. No variables and no return
  2. Variable and no return
  3. No variable and a return
  4. 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:


useless()

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:

wpid-pyhton_basic_menu-2013-12-23-10-21.png

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:

wpid-python_functions_errors_1-2013-12-23-10-21.png

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:


ho()

ho(5)

The output will be:

wpid-python_ho_function_output-2013-12-23-10-21.png

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)

wpid-python_power_function_output-2013-12-23-10-21.png

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.

Happy Holidays!

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
  • Pingback: Introduction to types of Functions in Python | Boardmad...a road slightly less travelled

  • Pingback: Captain DeadBones” Chronicles: Introduction to Functions in Python | The Black Velvet Room

  • João Sebastião de Oliveira Bue

    print str(base) + " to the power of " + str(exp) + " is ",power(base,exp)

    Sorry - but I don think you are doing any service to Python by teaching constrcuts like this. Python- spowerfull options for string interpolations are one o the strong point of the language - and no "I will soho only one thing at once" should justify this idion that is hard to type, and nearly impossible to read.

    • CptDeadBones

      Thanks for the comment. However, I do not understand, how would you like that line written?

      • João Sebastião de Oliveira Bue

        For exampĺe:
        print "%d to the power of %d is %d " % (base, power, power(base,exp) )

        • CptDeadBones

          I see. That os another valid option to print, however, in my mind that is closer to C. The real power of Python is the ability to write simple code from scratch, not to complete things. I prefer my way better since it will still work if you change the type of data. For example, lets say the base is 3.14. If we used you print statement as is it will truncate the decimal portion. My print statement will leave it as is without modifying the print statement.

          • João Sebastião de Oliveira Bue

            Replace the "%d"s in my snippet by "%s" , and it will work or ay kindo f data as well. BTW, there is another, big, flaw on your example: you are using Python-2's input statement, which performs an automatic "eval" on the value typed in. That is strongly discouraged - in Python 2 in favor of "raw_input", with explicit conversion of the values, and in Python 3, the eval behavior is supressed for once.

          • CptDeadBones

            I still hold that my print statements are my preferred way. That does not mean that I am right or wrong, it is just how I like it. I do agree with you that I should not be using input statements and that I should be using raw_input in python 2.7. It was a quick hack, I should have payed more attention. I will try to do better next time. Thanks for pointing that out.