Functions and Modules

Reference Document

What is a Function?

  • A block of organized, reusable code that is used to perform a single, related action.
  • Provides better modularity for your application and a high degree of code reusing.
  • You can name a function anything you want as long as it:
    1. Contains only numbers, letters, underscore
    2. Does not start with a number
    3. Is not the same name as a built-in function (like print).

Basic Synthax of a Function


In [ ]:
from IPython.core.display import Image 
Image(filename='diagramFunction.png')

An Example


In [ ]:
def int(x,y):
    return x + y

In [ ]:
type(1) == int

In [ ]:
print addnums(0x1f,3.3)

In [ ]:
print addnums("a","b")

In [ ]:
print addnums("cat",23232)

Scope of a Function


In [ ]:
def numop(x,y):
    x *= 3.14
    return x + y
x = 2
print numop(x, 8)
print x

Python has it’s own local variables list. x is not modified globally ...unless you specify that it’s a global variable


In [ ]:
def numop(x,y):
    x *= 3.14
    global a    
    a += 1
    return x + y, a

a = 2
numop(1,1)
numop(1,1)

Pass by reference vs value

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.


In [ ]:
def changeme_1( mylist ):
   mylist = [1,2,3,4]; # This would assig new reference in mylist
   print "Values inside the function changeme_1: ", mylist
   return

def changeme_2( mylist ):
   mylist.append([1,2,3,4]);
   print "Values inside the function changeme_2: ", mylist
   return

In [ ]:
mylist1 = [10,20,30];
changeme_1( mylist1 );
print "Values outside the function: ", mylist1
print

In [ ]:
mylist2 = [10,20,30];
changeme_2( mylist2 );
print "Values outside the function: ", mylist2

Function Arguments

You can call a function by using the following types of formal arguments:

  • Required arguments (arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition)
  • Keyword arguments (identified by parameter names)
  • Default arguments (assume default values if values are not provided in the function call for those arguments)
  • Variable-length arguments (are not explicitly named in the function definition)

Keyword Arguments


In [ ]:
def numop1(x,y,multiplier=1.0,greetings="Thank you for your inquiry."):
    """ numop1 -- this does a simple operation on two numbers.
     We expect x,y are numbers and return x + y times the multiplier
     multiplier is also a number (a float is preferred) and is optional.
    It defaults to 1.0.
     You can also specify a small greeting as a string. """
    if greetings is not None:
       print greetings
    return (x + y)*multiplier

In [ ]:
help(numop1)

In [ ]:
numop1(1,1)

In [ ]:
numop1(1,1,multiplier=-0.5,greetings=None)

Unspecified args and keywords


In [ ]:
def cheeseshop(kind, *arguments, **keywords): 
    print "-- Do you have any", kind, "?"
    print "-- I'm sorry, we're all out of", kind 
    for arg in arguments: 
        print arg
    print "-" * 40
    keys = keywords.keys()
    keys.sort()
    for kw in keys: 
        print kw, ":", keywords[kw]

In [ ]:
cheeseshop("Limburger", 
           "It's very runny, sir.", 
           "It's really very, VERY runny, sir.",
           shopkeeper='Michael Palin',
           client="John Cleese",
           sketch="Cheese Shop Sketch")

What is a Module?

  • A Python object with arbitrarily named attributes that you can bind and reference.
  • A file consisting of Python code.
  • Allows you to logically organize your Python code.
  • Makes the code easier to understand and use.
  • Can define functions, classes and variables.
  • Can also include runnable code. </UL>
  • Any file ending in .py is treated as a module.
    
    
    In [ ]:
    # %load "numfun1.py"
    #!/usr/env python
    
    """
    small demo of modules
    """
    def numop1(x,y,multiplier=1.0,greetings="Thank you for your inquiry."):
        """ 
        numop1 -- this does a simple operation on two numbers.
                  We expect x,y are numbers and return x + y times the multiplier.
                  multiplier is also a number (a float is preferred) and is 
                  optional. It defaults to 1.0.
                  You can also specify a small greeting as a string.
        """ 
        if greetings is not None:
           print greetings
        return (x + y)*multiplier
    
    
    
    In [ ]:
    # %load "numfun1.py"
    #!/usr/env python
    
    """
    small demo of modules
    """
    def numop1(x,y,multiplier=1.0,greetings="Thank you for your inquiry."):
        """ 
        numop1 -- this does a simple operation on two numbers.
                  We expect x,y are numbers and return x + y times the multiplier.
                  multiplier is also a number (a float is preferred) and is 
                  optional. It defaults to 1.0.
                  You can also specify a small greeting as a string.
        """ 
        if greetings is not None:
           print greetings
        return (x + y)*multiplier
    
    
    
    In [ ]:
    numfun1.numop1(2,3,2,greetings=None)
    
    
    
    In [ ]:
    numop1(2,3,2,greetings=None)
    
    
    
    In [ ]:
    # %load "numfun2.py"
    #!/usr/env python
    
    """
    small demo of modules
    """
    
    print "numfun2 in the house"
    x  = 2
    s  = "spamm"
    
    def numop2(x,y,multiplier=1.0,greetings="Thank you for your inquiry."):
        """ 
        Purpose: does a simple operation on two numbers.
    
        Input: We expect x,y are numbers
               multiplier is also a number (a float is preferred) and is optional.
               It defaults to 1.0. You can also specify a small greeting as a string.
    
        Output: return x + y times the multiplier
        """ 
        if greetings is not None:
           print greetings
        return (x + y)*multiplier
    
    
    
    In [ ]:
    
    
    
    
    In [ ]:
    print numfun2.x, numfun2.py
    
    
    
    In [ ]:
    s = "eggs"
    print s, numfun2.s
    
    
    
    In [ ]:
    numfun2.s = 'jack'
    print s, numfun2.s
    

    Import Statements

    from module_name import name as my_name from module_name import function_name from module_name import variable from module_name import variable, function_name1, function_name2, ... from module_name import *
    
    
    In [ ]:
    from numfun2 import x, numop2
    
    
    
    In [ ]:
    x == 2
    
    
    
    In [ ]:
    numop2(2,3,2,greetings=None)
    
    
    
    In [ ]:
    numfun2.s
    
    
    
    In [ ]:
    numfun2.x
    
    
    
    In [ ]:
    from numfun2 import s as my_fav_food
    from numfun2 import numop2 as awesome_adder
    
    
    
    In [ ]:
    print my_fav_food
    
    
    
    In [ ]:
    print numfun2.s
    
    
    
    In [ ]:
    awesome_adder(2,3,1)
    
    
    
    In [ ]:
    import numfun2
    
    
    
    In [ ]:
    from numfun2 import *
    
    
    
    In [ ]:
    from numfun2 import x
    

    Built-In-Modules

    • sys: exposes interpreter stuff & interactions
    • os: exposes platform-specific OS functions
    • math: basic mathematical functions & constants
    • argparse: command line parser
    
    
    In [ ]:
    
    

    Breakout Session: Exploring Some Modules

    1. Create and edit a new file called age.py
    2. Within age.py, import the datetime module
      • use datetime.datetime() to create a variable representing when you were born
      • subtract the two, forming a new variable, which will be a datetime.timedelta() object. Print that variable.
        1. How many days have you been alive? How many hours?
        2. What will be the date in 1000 days from now?
    
    
    In [ ]:
    import datetime
    y = datetime.datetime.now()
    print y
    
    
    
    In [ ]:
    x = datetime.datetime(2016,6,13)
    y-x
    
    
    
    In [ ]:
    help(datetime)
    
    
    
    In [ ]: