You will of already come across some functions already in VB just may not of been aware of it. They are a powerful feature of programming but one which takes a little while to get used to. A lot of students will not see the value of functions initially. Mainly as they require more work to produce a program which does the same thing. However as your code gets bigger and the more people who are working on the code the more important functions become.

Consider the following example. There are five students who have taken two tests. The teacher wants to know which tests the students did better in to help them with their revision. The results are below.

Name

Test 1

Test 2

Bert

8

3

Fiona

5

7

Sally

7

6

George

7

7

Fred

5

4

We can write some code to help us with this task.

 


name = "Bert" 
test1 = 8 
test2 = 3 
if test1 > test2: 
	print (name + "did better on test 1"
elif test1 < test2: 
	print name + "did better on test 2"
else: 
	print name + " did equally well on both tests"

#This code will display what test Bert did best on. 
#Now we will do the same for Fiona.
name = "fiona" 
test1 = 7 
test2 = 7 
if test1 > test2: 
	print (name + "did better on test 1"
elif test1 < test2: 
	print name + "did better on test 2"
else: 
	print name + " did equally well on both tests"

The code in bold is what has changed from the first set of code. As you can see it is only the assignment of the three variables. This is very wasteful but also very problematic. If we copy and paste this code the full 5 times we will of repeated the normal type faced code 5 times. Problems could arise if there was a problem in the code. You would then have to fix the problem 5 times!

Functions allow an elegant solution to this problem. We can store the code once, five it a name, and then run in numerous times. Consider the solution below

 


def compareTests(name, test1 , test2):
	if test1 > test2 then 
		print  name + " did better on test 1"
	elif test1 < test2: 
		print name + " did better on test 2" 
	else:
		print name + " did equally well on both tests"

compareTests("Bert", 8,3) 
compareTests("Fiona", 5,7) 
compareTests("Sally", 7,6) 
compareTests("George", 7,7) 
compareTests("Fred", 5,4) 

The code is basically split into two parts. The function definition and the function calls. The code insde the function has not changed from the previous example. The only difference is that we are calling the code 5 times rather than duplicating the code 5 times. This means that it makes the code much shorter, much neater and also less error prone. If there was a bug in the code we would only need to fix it in one place. The only problem with this approach is that it is a little more difficult to understand.