Functions

You have already been using a function called main(). In this section we will be looking at how to define other functions and how to call them. You can think of a function as a small piece of code that has one specific functionality. Functions need to be called. They can be called within main() or within other functions. A function could also call itself, defining what we call recursive functions. Depending on what the function was intended to perform, it may or may not return a value or values.

The structure of a function definition is as follows:

  def function_name ([formal_parameters]):
    ...
    body_of_the_function
    ...
The function_name is an identifier in Python and obeys the same rules for its construction. The convention that we will be using in our class is that function names should be in lower case and should be indicative of its functionality. The formal parameters are optional. You can have zero or more parameters. However, even if you have no formal parameters, you must have the open and close parentheses. You can think of the formal parameters as placeholders that accept values sent to it from the calling function. When a function is called, the parameters that are passed to it are called actual parameters.

You have already seen and used some of the pre-defined functions in Python. You can call these functions simply by name:

  x = -4.7
  y = abs (x)     # y = 4.7
  z = int (x)     # z = -4
Here is a complete list of built-in functions.

There are other functions that reside in modules that have to be loaded before you can use them like string, math, and random. You load these modules by using the import directive.

  import string
  import math, random
After you load the module you can call on the functions using the dot operator.
  x = 7
  y = math.sqrt (x)
  z = random.random()

To call a user defined function that is in the same program you simply call it by name without using the dot operator. If the function does not return a value, then call it on a line by itself. If it returns values then assign those return values to the corresponding variables.

  def addTwo (a, b):
    return a + b

  def divide (a, b):
    return a / b, a % b

  def isEven (x):
    return (x % 2 == 0)

  def gcd (m, n):
    while (m != n):
      if (m > n):
        m = m - n
      else:
        n = n - m
    return m

  def coPrime (a, b):
    if (gcd(a, b) != 1):
      return
    else:
      print "%0d and %0d are co-prime" % (a, b)

  def main():
    x = 2
    y = 3

    z = addTwo (x, y)

    p, q = divide (x, y)

    if (isEven(z)):
      print z
    
    coPrime (x, y)

  main()