A group of statements that exist within a program for the purpose of performing a specific task

Python functions

A function is a group of statements that exist within a program for the purpose of performing a specific task. Instead of writing a large program as one long sequence of statements, it can be written as several small functions, each one performing a specific part of the task.

A function is a reusable portion of a program, sometimes called a procedure or subroutine.

  • Like a mini-program (or subprogram) in its own right
  • Can take in special inputs (arguments)
  • Can produce an answer value (return value)
  • Similar to the idea of a function in mathematics

Why write and use functions?

  • Divide-and-conquer
    • Can breaking up programs and algorithms into smaller, more manageable pieces
    • This makes for easier writing, testing, and debugging
    • Also easier to break up the work for team development
  • Reusability
    • Functions can be called to do their tasks anywhere in a program, as many times as needed
    • Avoids repetition of code in a program
    • Functions can be placed into libraries to be used by more than one "program"

With functions, there are 2 major points of view

  • Builder of the function -- responsible for creating the declaration and the definition of the function (i.e. how it works)
  • Caller -- somebody (i.e. some portion of code) that uses the function to perform a task

Using functions

  • The user of a function is the caller.
  • Use a function by making calls to the function with real data, and getting back real answers.
  • Consider a typical function from mathematics:
      f(x) = 2x + 5
    
    In mathematics, the symbol 'x' is a placeholder, and when you run the function for a value, you "plug in" the value in place of x. Consider the following equation, which we then simplify:
      y = f(10)		// must evaluate f(10)
      y = 2 * 10 + 5	// plug in 10 for x
      y = 20 + 5
      y = 25		// so f(10) gives the answer 25
    
    In programming, we would say that the call f(10) returns the value 25.
     
  • Python functions work in largely the same way. General format of a Python function call:
     functionName (argumentList)
    
    where the argumentList is a comma-separated list of arguments (data being sent into the function). Use the call anywhere that the returned answer would make sense.
     

Building functions

  • The builder of a function (a programmer) is responsible for the definition (i.e. how it works).
  • The structure of a function:
    def functionName (parameters): # known as the function header
       statements(s)
       ...
    
  • The pieces
    • Function header begins with the key word def.
    • functionName - identifier chosen by the builder
    • parameters - a comma-separated list of the parameters that the function will receive. This is data passed IN to the function by the caller. The parameter list indicates the order, and number of parameters
    • function body - code statements that make up the definition of the function and describe what the function does, how it works
  • Value-returning functions are special type of functions. It is like a regular function, however, when the function is finished executing its statements it returns a value back to the part of the program that called it. The structure of a function:
    def functionName (parameters): # known as the function header
       statements(s)
       ...
       return expression
    
  • A return statement will force immediate exit from the function, and it will return the value of the expression to the caller.

Calling a function

  • A function definition specifies what a function does, but needs to be called to execute it. Example:
    # This program demonstrates a function.
    # First, we define a function named message.
    def message():
        print 'I am Arthur'
        print 'King of the Britons'
    
    # Call the message function.
    message()
    				
  • Many function can exist together:
    # This program has two functions. First we
    # define the main function.
    def main():
        print 'I have a message for you.'
        message()
        print 'Goodbye!'
        
    # Next we define the message function.
    def message():
        print 'I am Arthur'
        print 'King of the Britons.'
    
    # Call the main function.
    main()
    
    
  • The main function is a common function to have. It typically contains a programs mainline logic (overall logic of the program).
  • Just as in our conditional and repetition control structures (if-else, while, and for) indentation is important.

Scope of Identifiers

  • The scope of an identifier (i.e. variable) is the portion of the code where it is valid and usable
  • A variable declared within a block (i.e. a compound statement) of normal executable code has scope only within that block.
    • Includes function bodies
    • Includes other blocks nested inside functions (like loops, if-statements, etc)
    • Does not include some special uses of block notation to be seen later (like the declaration of a class -- which will have a separate scope issue)
  • Variables declared in the formal parameter list of a function definition have scope only within that function.
    • These are considered local variables to the function.
    • Variables declared completely inside the function body (i.e. the block) are also local variables
  • Bad function variable scope:
    # Definition of the main function.
    def main():
        get_name()
        print 'Hello', name     # This causes an error!
    
    # Definition of the get_name function.
    def get_name():
        name = input('Enter your name: ')
    
    # Call the main function.
    main()
    				
  • Example showing some variables with different scopes
  • Variables declared outside of all functions in a file are revered to as global variables.
    # Create a global variable.
    my_value = 10
    
    # The show_value function prints
    # the value of the global variable.
    def show_value():
        print my_value
    
    # Call the show_value function.
    show_value()
    					
    Code: global1.py
  • To assign values to global variables you have to use the keyword global:
    # Create a global variable.
    number = 0
    
    def main():
        global number
        number = int(input('Enter a number: '))
        show_number()
    
    def show_number():
        print('The number you entered is', number)
    
    # Call the main function.
    main()
    					
    Output:
    Enter a number: 13
    The number you entered is 13
    					
    Code: global2.py
  • A global constant is a global name that references a value that cannot be changed. In Python it isn't possible to create a true constant variable. However, without the use of the global keyword the global variable can not be changed (Remember to identify variables as constant by using all caps for their names.)
    MY_CONSTANT = 0.0
    def main():
       print MY_CONSTANT  # Prints the value of the global constant. 
       MY_CONSTANT = 9.0  # This is a new variable with scope in the main function only.						
    						

Function parameters and using keyword return

  • Parameter lists
    • Mathematical functions must have 1 or more parameters
    • Python functions can have 0 or more parameters
    • To define a function with no parameters, leave the parentheses empty
    • Same goes for the call. (But parentheses must be present, to identify it as a function call)
    • Since variables in Python are references the parameter variable refers to the same variable as the variable reference that is passed.
      def main():
         name = "My Name"
         print "Your name is: ",name
         pass_name(name)
         
      def pass_name(n):
         print "The name passed is: ",n
         
      main()
      							
      Output:
      Your name is:  My Name
      The name passed is:  My Name
      							
    • Changing the parameter value does not affect the original variable where it was passed in:
      # This program demonstrates what happens when you
      # change the value of a parameter.
      
      def main():
          value = 99
          print 'The value is', value
          change_me(value)
          print 'Back in main the value is', value
      
      def change_me(arg):
          print 'I am changing the value.'
          arg = 0
          print 'Now the value is', arg
      
      # Call the main  function.
      main()
      Output:
      The value is 99
      I am changing the value.
      Now the value is 0
      Back in main the value is 99
      
      Code: change_me.py
    • Python allows parameters to be passed as keyword arguments. Traditionally, arguments are passed to the function in the order they are listed:
      def main():
         var1 = 0
         var2 = 1
         var3 = 2
         
         # parameters used in the order they are passed
         my_function(var1, var2, var3) 
      
         # Keyword arguments specifies which parameter the 
         # arguments should be passed into as.
         # Its position in the function call does not matter.
         my_function(param3=var3, param1=var1, param2=var2)
      
      
      def my_function(param1, param2, param3):
         print "Params: ", param1, param2, param3
         
         
      main()
      						
      Output:
      Params:  0 1 2
      Params:  0 1 2
      						
  • value-returning functions
    • A mathematical function must return exactly 1 answer
    • A Python function can return 0 or more return values
    • A function not returning anything, can still use the keyword return inside, but not with an expression (only by itself). One might do this to force early exit from a function.
    • To CALL a function that doesn't return a value, call it by itself -- do NOT put it in the middle of any other statement or expression
    • The return call can contain expressions that can simply your code:
      def sum(num1, num2):
         result = num1 + num2
         return result
      						
      Alternatively:
      def sum(num1, num2):
         return = num1 + num2
      							
    • A value-returning functions can be used as part of expressions:
      def main():
         print "Lets calculate the average of two numbers."
         ave = (get_value() +  get_value()) / 2.0
         print "Average: ", ave
         
      def get_value():
         return input("Enter a number: ")
      
      main()
      						
      Output:
      Lets calculate the average of two numbers.
      Enter a number: 10
      Enter a number: 58
      Average:  34.0						
      						
      Code: value_return.py
    • Functions can also return multiple values: return expression1, expression2, etc.
      def get_name():
         #Get the users first and last name.
         first = raw_input("Enter your first name: ")
         last  = raw_input("Enter your first name: ")
         
         # Return both names.
         return first, last
      
      def main():
         # Values are assigned in the order they are returned.
         # The number of variables has to match the number of
         # return values.
         firstName, lastName = get_name()
         
         print firstName, lastName
         
      main()							
      							
      Output:
      Enter your first name: First
      Enter your first name: Last
      First Last
      							
      Code: multi_return.py
  • Code example with definitions and calls for these functions

What do we call a series of statements that performs a task?

A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. The Function procedure performs a task and then returns control to the calling code.

Which of the following is a group of statements which are part of another statement?

Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way.

What statement do you have in a value returning function?

To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.

What term is used to describe the portion of a program in which a variable can be accessed?

Variable Scope. A variable's scope determines where in a program a variable is available for use. A variable's scope is defined by where the variable is initialized or created.