Functions
We have already shown the functions that are built into Python. Although there is a wealth of functions available to us, there will be times that you need to create your own. In some other programming languages, functions are known as subroutines.
There are usually two reasons for functions. The first is to organize the code into a logical way to handle certain tasks. The other is to be able to reuse code. The general rule of thumb is that if you have a block of code that gets called more than once, put it in a function.
Structure of a Function
The structure of a function is very simple but very important.
def {FunctionName}[(parameters)]: # Function Header
Indented code..... # Code begins here
The header of a function defines the way it will be called. The header begins with the def keyword followed by the function name, then the optional parameter list and a colon. Even if there are no parameters, you must place parenthesis before the colon (e.g., def Toad(): ). All code for the function must be indented. The function name must follow the same naming rules for variables (Single word, No spaces, must start with either a letter or an underscore, etc). The optional parameter list contains variable names (preferably not used anywhere else) seperated by commas. The header ends at the colon.
The next line begins the function code and must be indented.
def CountUp(HowHigh):
for Cntr in range(1,HowHigh+1):
print(Cntr)
In this case, the function name is CountUp and there is one parameter, HowHigh. Notice that we don’t have to declare what the type is for the parameter; it will be determined by the interpreter. Our code has just two lines, a for loop and a print statement.
Some people who have experience with other programming languages might say that this is a procedure, not a function, because it doesn’t return anything. In some other programming languages, this might be true, but not in Python. In a case such as this, the function actually does return something, the None value.
Returning values
There will be times that your function needs to return one or more values. We use the return keyword to do this.
In the following example, we define a function called TestFunction that takes two values. The code simply returns the values back to the calling line. When we call the function, we assign two variables (a and b) to hold the two returned values.
def TestFunction(val1,val2):
return val1,val2
a,b = TestFunction(3,2)
print('Returned from function... a = %d, b = %d' % (a,b))
Returned from function... a = 3, b = 2
Optional Parameters
Sometimes you need to provide for the possibility of optional parameters. For example, you want to add functionality if a second value is provided. Many times this could be a flag for the code. We do this by assigning a default value for that parameter. In the following code snippet, we define a function with a required parameter (val1) and an optional parameter (val2), which is assigned 0 as its default value. If the function is called with one parameter value, val2 will default to 0. One word of caution about using optional or default parameters: They are evaluated when the function is defined, not when the program is run. In the following example, we are safe because we are using a default of 0. However, if you set a default value for a parameter that is the result of another function (such as a time), it could cause great heartache and make you beat your head upon the keyboard for hours.
def TestFunction2(val1, val2=0):
print('Required value = %d' % val1)
if val2 != 0: # Only print the line below if val2 was provided
print('Optional value = %d' % val2)
TestFunction2(1) # call function with only one value
print('')
TestFunction2(1,2) # call function with two values
Required value = 1
Required value = 1
Optional value = 2
You might realize that if val2 was passed a 0, the second line would not print. You can get around this issue by setting the default value for val2 to be None, as this code shows.
def TestFunction2(val1, val2=None):
print('Required value = %d' % val1)
if val2 != None:
print('Optional value = %d' % val2)
TestFunction2(1)
print('')
TestFunction2(1,0)
Variables in and out of Functions
Where and how variables are defined determines when they may be changed. If we define a variable within a function or pass a value to a function, the value of that variable is only really accessable within that function. This is called scope.When we pass a variable to a function, what actually is passed is a reference to that variable.
Example 1
a = 5
def test(a):
print('A = %d' % a)
a += 10
print('A is now %d' % a)
print('A starts with %d' % a)
test(a)
print('After test function a = %d' % a)
Here’s what the program is supposed to do followed by its output.
Output
A starts with 5
A = 5
A is now 15
After test function a = 5
If you are surprised by this, you have to remember two things. The variable ‘a’ was defined outside of the function, and even though we changed the value passed in to 15, that value is strictly local to the function. We didn’t actually change ‘a’.
This could be looked at as a double edged sword. On the one hand, the value in any variable passed to a function is safe from manipulation. On the other hand, sometimes we actually need to change that value.
Example 2
There are two ways to change the value. The first way is to use the global keyword within the function. The second is to return a value.
Using Global Keyword
a = 1
def test1():
a = 42
print('Inside test1...a = %d' % a)
def test2():
global a
a = a + 1
print('Inside test2...a = %d' % a)
print('a starts at %d' % a)
test1()
print('After test1, a is now %d' % a)
test2()
print('After test2, a is now %d' % a)
Output
a starts at 1
Inside test1...a = 42
After test1, a is now 1
Inside test2...a = 2
After test2, a is now 2
Return a Value
Here is the same program we used earlier but modified to return the changed variable.
a = 5
def test(a):
print('A = %d' % a)
a += 10
print('A is now %d' % a)
return a
print('A starts with %d' % a)
a = test(a)
print('After test function a = %d' % a)
Output
A starts with 5
A = 5
A is now 15
After test function a = 15
Anatomy of a Python Program
Let’s review the structure and an actual example.
Structure of a simple program
A simple python program has the following structure:
Shared Variable Declarations
Functions
Main Routine
A real example
So it would look something like this:
a = 24
b = 42
def function1(varA,varB):
print(varA,varB)
def main():
function1(a,b)
#...
main()
In this program example:
The exception to this generic template would be if we are writing a program that includes classes, which are discussed in detail in Chapter 10.