| CMSC 201 |
Lab 6: FunctionsFunctionsWhat 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, val3for 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()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 |