CMSC 201

Lab 6: Functions

Functions

What are they?

A functions is basically a block of code with a name and it's own set of variables. You can use this name to execute the block of code as many times as you want to.

Ideally, all statements inside the function should work towards a similar purpose. For example, you might write a function to print out a square, and another one to print out a triangle, but you would not put both of those actions in the same function because they are unique.

What do they look like?

The first line of the function contains it's name and any of it's parameters, followed by a colon. Note: there do not have to be any parameters. Then you put any code you want inside of the function on the following lines, all indented. The indentation is like a for loop, while loop, or if statement.

A function with no parameters:


def myFirstFunction():

	//some code...

	//some more code...

A function with 2 parameters:

def mySecondFunction(param1, param2):

	sum = param1 + param2

	difference = param2 - param1

	product = param1 * param2

Part of the power of functions is the ability to return values. When you return a value, wherever you called the function gets replaced by that value. To return a value, use the return keyword followed by whatever you want to return. Without using return, you cannot access any of the variables you define inside of the function from outside of the function.


def findSum(numA, numB):

	sum = numA + numB

	return sum

You can even return more than one value in what is called a tuple. To do this, simply use

return val1, val2, val3
for however many values you want to return.

How do I use functions?

To use a function, simply call it by name. The following are all valid function calls:


//will do whatever code is inside of myFirstFunction()

myFirstFunction()


//will do whatever code is inside of mySecondFunction and param1 and param2 will take on the values 4 and 5 like I have given: mySecondFunction(4, 5) //notice that inside of mySecondFunction, sum will be 9, //difference will be 1, and product will be 20. //These values are not accessible unless they are returned from the function.
//This will place the value returned from findSum into my variable mySum, //but will not change the value of sum(notice this particular variable named sum is not in the function definition). sum = 3 mySum = findSum(3, 12) //Now mySum = 15, and sum is still 3. This is because it is different than the variable sum defined inside the function findSum
Returning multiple variables is slightly more challenging.

def multipleVariableFunction(numA, numB, numC):

	numD = numA + 1

	numE = numB + 1

	numF = numC + 1

	return numD, numE, numF


myNumA = 5 myNumB = 9 myNumC = 15 myNumD, myNumE, myNumF = multipleVariableFunction(myNumA, myNumB, myNumC) //now, myNumD will be 6, myNumE will be 10, myNumF will be 16