CHAPTER 8

image

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.

  1. Define a variable called ‘a’ and assign it to a value of 5.
  2. Define a function called test that takes a parameter also called ‘a’. Note that this is not the same variable.
  3. Once we are in the function, we print the value of a (an assumption that ‘a’ is a decimal number is made here).
  4. Add 10 to that value and print the new value. That is the end of the function and we do not return any values.
  5. The program actually starts with the first line (a = 5) then skips the function and continues with the next nonindented line (‘print(‘A starts . . . ’). So we assign 5 to variable a, then we print “A starts with 5“.
  6. Call the function test with the variable a, which is 5, as the parameter.
  7. Inside the function, we print “A = 5“, then add 10 to it and print “A is now 15“. When we exit the routine, we then print “After test function a = “ and the value of  ‘a’.

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)

  1. First we define a variable 'a' and assign the value of 1 to it.
  2. Next we define two functions, test1 and test2. Neither of them will take a parameter
  3. In the test1 function, we assign a variable 'a' and assign the value of  42 to it and print the value. Remember that this variable 'a' has a different scope which is strictly only for use within this function.
  4. In test2, we use the global keyword when we define the variable 'a'. This time, because we used the global keyword, we are saying that anytime we use the variable 'a', it should refer to the global variable, not a local one. Now anything that happens to the variable 'a' within the routine will change the one declared in the first line of code.
  5. Now the code continues and will print "a starts at 1", procedes to call fuction test1, which creates its own variable 'a', assigns the value of 42 to it and does the print.
  6. When we come back from that, we print "After test1, a is now 1".
  7. The function test2 is called next. Because we have declared that the variable 'a' in the function is the global one, it gets changed to 2 and we do the print, then on return from the function, we get "After test2, a is now 2".

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)
  1. You can see that we only added one line (the "return a" line and modified the call to the test function by assigning the variable to pick up the return value.
  2. When this program runs . . . we assign 5 to variable 'a', pass it to the test function.
  3. It prints the value that was just passed in, increments it by 10, prints the new value (15) and then returns the new value, which is received by the call to the function and changes the value 'a' from 5 to 15.

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:

  1. We declare variables 'a' and 'b' so that they are global in scope.
  2. Next we declare two functions, one called ‘function1’ and one called 'main'.
  3. The comment line with the elipses simply shows that there may be more functions below that.
  4. The last line calls the function ‘main’ to start the program.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset