Python Notes - Functions - def

Contents   Installing Python   Variables   Input/Output   if   while   Functions - def   Scopes (local/global)   Function parameters   Lists (arrays)   Dictionaries   Tuples   Files   Libraries   Hints, tips  

A function is a named section of program. We can refer to a lot of code by its name, rather than cutting and pasting it.

Let us look at an example, with 3 functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#game messages
def welcome():
    print "Welcome to the game of Real Life"
    author()                 # a call
    print "Have Fun !!!"
  
def bye():
    print "Goodbye"
    print "Play again soon"
  
def author():
    print "Written by Hucks Brown"
    print "and Champion Jack Dupree"
 
#some calls
welcome()
bye()
The output is:


Welcome to the game of Real Life
Written by Hucks Brown
and Champion Jack Dupree
Have Fun !!!
Goodbye
Play again soon

Note:
  • Our program has 3 functions. We chose to name them:
    
    welcome
    author
    bye
    
  • A function is introduced by def, meaning define. The code associated with a function (the body) is indented, and ends when the indent ends. Thus, the code of function welcome goes from line 2 to 5.
  • To get a function to do its job, we 'call' or 'invoke' it, by mentioning its name, as in:
    welcome()
    
    
  • Note the 'empty brackets' () in the call and the define. Later , we will put something inside the ( ).
  • Here is the order in which the lines are executed:
    16   2 3 4   11 12 13   5   17  7 8 9       terminates 
    

How it works

The program executes from top to bottom, as normal, but when a def is encountered, Python memorises it, rather than executing it. In our program, the first line NOT part of a function is line 16, the call of welcome. The program transfers control to the welcome function at line 2, and starts obeying instructions. It executes line 3 as normal, but then encounters a call of the author function.

Execution transfers to line 7, and the 2 prints within author are executed.

We have now hit the end of author. Python returns to the function which called author, to the point just beyond where it was called from - line 5. Line 5 executes, and then we find that the welcome function has hit its end, so it returns to the point just after it was called from. It was called from line 16, so we return back to 17.

17 executes - bye is called. The bye function prints two lines, and returns to just beyond where it was called from - the line after 17. In fact, there is no 18, so the program terminates normally.

Pictorially, the use of author is:


 _                                                                    _ 
|                                                                      |

                      call                 +----------------+           
        author()--------------------}----  | def author():  |          
        next line  ---------+              |     print .... |           
                   return   |              |     print .... |           
                            + ----{------  +----------------+          
                                                                       

|_                                                                    _|

Note that author does not know - in general - where it might be called from. It can be called several times, and from different places. Python keeps track of the calls.

Communicating with Functions - global/local scope

The above had no variables, but here we return to our area program, breaking it down into several functions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#area - functions - v1
width = 0
height = 0
area = 0
 
def main():
    getSize()
    calcArea()
    showResults()
#end def
  
def getSize():
   global width, height
    width = input("Type the width")
    height = input("Type the height")
#end def
  
def calcArea():
    global width, height, area
    area = height * width
#end def
  
def showResults():
    global area
    print "Area is ", area, "Sq Metres"
    print "---------------------------"
#end def
  
main()  #execution begins here
Note:
  • Our program has 4 functions. We chose to name them:
    
    main
    getSize
    calcArea
    showResults
    
    One style of function usage involves coding a top-level function. Here, the use of a 'main' shows the concept of a boss, or top-level controller, whose main purpose is to call up functions to get the job done. Thus, functions call other functions. (The use of the name 'main' rather than say 'boss' is traditional in other languages. So, main is called first, because its call is the first instruction not within a def. In its turn, main calls getSize, calcArea, showResults
  • Note that (for example) the values obtained by getSize have to made available to calcArea.

  • We need to re-visit the assignment concept, as in: a = 3 The use of = creates a variable if one did not previously exist. However, if such an instruction occurs inside a def, then the variable a can only be used within that def - it is termed a local variable. When the end of the def is reached, any local variables are erased. They are temporary.

    But - if we put

    a = 3
    at the top of the code, outside any def regions, then a can potentially be used by any functions. Its scope is termed global rather than local.

    Analogy, in a class of students, each might make their own notes - local. The blackboard can be used by anyone, and seen by everyone - global.

  • There is one more task in Python. Any function which wants to use global variables must say so with a global instruction, as in:
    a = 3
    
    def someFunction():
        global a
        a = a + 1       # a is now 4
    
    
    If we omitted the global a then a local a would be used (this does not cover all the cases, but is close enough to get by!)
  • Note that we only use global where it is needed - thus, showResults only needs to know about area, not width and height.
  • as a minor point, we have chosen to put #end def comments in. These are optional
Strictly, we don't need to introduce the variable at the top of the code, but we suggest you do this, as it is closer to other languages (Java, VB, c++) that you may encounter.
Problem: amend the program so it calculates the volume of a box. Amend the voume program so that it displays the 3 input values in showResults, along with thew volume.

Function Parameters, Return, and Local Variables...

Are important. They are in a following chapter!

Menus Example

Here is the menu program we did in the While section. We have added a sub-menu. Using functions makes the structure clearer. Type a to get to the sub-menu. To get out of the sub-menu, type stop. This takes you back to the main menu. This is rather like a cellphone menu system. It might be useful to incorporate in some programs. The modern way is to have a point-and-click menu, of course, and this is introduced in the GUI chapter.

#sub-menu, with functions
def main():
    topMenu()
#end def

def topMenu():
    reply = raw_input("Choose a(sub-menu), b, c, or stop: ")
    while reply !="stop":
        if reply =="a":
            print "choice a"
            subMenuA()
        elif reply=="b":
            print "choice b"
        elif reply == "c":
            print "choice c"
        else:
            print "error in choice"
        #end if
        reply = raw_input("Choose a(sub-menu), b, c, or stop: ")
    #end while
    print "Done"
#end def

def subMenuA():
    reply = raw_input("Sub-menu A. Choose x, y, z or stop: ")
    while reply !="stop":
        if reply =="x":
            print "choice x"
        elif reply=="y":
            print "choice y"
        elif reply == "z":
            print "choice z"
        else:
            print "error in choice"
        #end if
        reply = raw_input("Sub-menu A. Choose x, y, z or stop: ")
    #end while
    print "Done sub-menu A  - back to top menu"
#end def

main()

-------

Contents   Installing Python   Variables   Input/Output   if   while   Functions - def   Scopes (local/global)   Function parameters   Lists (arrays)   Dictionaries   Tuples   Files   Libraries   Hints, tips