Lecture 4 — Using functions and modules


  • Material for this lecture is drawn from Chapter 4 of Practical Programming.
  • We will first concentrate on functions for different data types. Python already comes with many functions that we can use to solve lots of interesting problems.
  • We will then talk about using existing modules, including the ones you write.
  • We will revisit all these concepts in later lectures.

What have we learnt so far?

  • So far, we have learnt three basic data types: integer, float and strings.

  • We also learnt some valuable functions that convert between these data types (int, str) and also those operate on strings.

    >>> name = "Neil Degrasse Tyson"
    >>> len(name)
    >>> (name+"! ")*3
    'Neil Degrasse Tyson! Neil Degrasse Tyson! Neil Degrasse Tyson! '
    >>> print "%s was a speaker in Commencement %d" %(name,2010)
    Neil Degrasse Tyson was a speaker in Commencement 2010
  • Python provides a number of functions that are already defined for you to use. These are called built-in functions.

  • We will see examples of these functions and experiment with their use in this class.

String Functions

  • There are many other very interesting and useful string functions that will learn throughout the semester. Here are some first set of functions:

    >>> name = "Neil Degrasse Tyson"
    >>> name.lower()
    'neil degrasse tyson'
    >>> lowername = name.lower()
    >>> lowername.upper()
    >>> lowername.capitalize()
    'Neil degrasse tyson'
    >>> lowername.title()
    'Neil Degrasse Tyson'
    >>> "abracadabra".replace("br", "dr")
    >>> "abracadabra".replace("a", "")
    >>> "Neil Degrasse Tyson".find(" ")
    >>> "Neil Degrasse Tyson".find("a")
    >>> "Neil Degrasse Tyson".find("x")
    >>> "Monty Python".count("o")
    >>> "aaabbbfsassassaaaa".strip("a")
  • All these functions take one or more values, and return a new value. But they are called in different ways. We must learn how each function is called. We will see the reason for the differences later in the semester.

    >>> episode = "Cheese Shop"
    >>> episode.lower()
    'cheese shop'
    >>> len(episode)
    >>> episode + "!"
    'Cheese Shop!'
  • Be careful, none of these functions change the variable that they are applied to.

Exercise Set 1

  1. Take a string in a variable called name and repeat each letters a in name as many times as a appears in name (assume the word is all lower case).

    For example,

    >>> name = "amos eaton"
    ## your code goes here
    >>> name
    'aamos eaaton'
  2. Given a string in a variable called name, switch all letters a and e (only lowercase versions). Assume the variable contains only letters.

    Hint: first replace each ‘a’ with ‘1’.

    >>> name = "Rensselaer Polytechnic Institute"
    ## your code goes here
    >>> name
    'Ranssalear Polytachnic Instituta'
  3. Suppose you are given a string with only letters. Write a program that transforms the string into a hashtag.

    For example, 'Things you wish you knew as a freshman' becomes '#ThingsYouWishYouKnewAsAFreshman'.

    >>> word = 'Bring back the swarm'
    ## your code here
    >>> word

How about numerical functions

  • Many numerical functions also exist. Let us experiment with some of these first. Note what they do.

    • abs()
    • pow()
    • int()
    • float()
    • round()
    • max()
    • min()
  • Let’s play around to see what they do!

Objects and Built_ins

  • All the functions we have seen so far are built-in to the core Python. It means that these functions are available when you start Python.

  • Type

    >>> help(__builtins__)

    to see the full list.

  • All variables in Python are objects.

  • Objects are abstractions:

    • They have a specific organization and structure to the data they store.
    • They have operations/functions — we call them methods — applied to access and manipulate this data.
  • Often functions apply to a specific object type, like a string. We have seen these functions for strings. Their call takes the form:


    For example:

    >>> b = 'good morning'
    >>> b.find('o', 3)

    It also works by:

    >>> 'good morning'.find('o', 3)
  • You can see all the functions that apply to an object type with help as well. Try:

    >>> help(str)


  • Modules are additional collection of functions and constants that provide additional power to Python programs.

  • Some modules come with Python, but are not loaded automatically. For example math module.

  • Other modules need to be installed first. We installed a number of external modules for this class, such as PIL for images. We will see the use of these modules later in the semester.

  • To use a function in a module, first you must load it into your program using import. Let’s see the math module:

    >>> import math
    >>> math.sqrt(5)
    >>> math.trunc(4.5)
    >>> math.ceil(4.5)
    >>> math.log(1024,2)
    >>> math.pi
  • We can get an explanation of what functions and variables are provided in a module using the help function

    >>> import math
    >>> help(math)

Exercise Set 2

  1. Write a Python program that computes the area of a circle. Your program should use the math module. Remember, the formula is

    a(r) = \pi r^2

  2. What happens when we type

    import math
    math.pi = 3

    and then use math.pi?

Different Ways of Importing

  • The way you import a module determines how you can use them in your program.

  • We can import only a selection of functions and variables:

    >>> from math import sqrt,pi
    >>> pi
    >>> sqrt(4)
  • Or we can give a new name to the module within our program:

    >>> import math as m
    >>> m.pi
    >>> m.sqrt(4)
  • Both of these methods helps us distinguish between the function sqrt and the data pi defined in the math module from a function with the same name (if we had one) in our program.

  • We can also do this (which is NOT recommended!):

    >>> from math import *

    Now, there is no name difference between the math module functions and ours. It is dangerous, better avoid it.

Program Structure

  • Now we have seen many different components of a program.

  • It makes sense to organize the program so that it is easy to see the flow of program

  • Follow the programming convention:

    • a single comment explaining your program purpose,
    • then, all variables and input commands
    • then, all computation
    • finally all output.
  • We will add more components to this program as time goes on.

  • In the rest of the class, we will first examine the following program structure and then write our own program to compute the the length of the hypotenuse of a triangle in the same format.

    """ Author: CS-1 Staff
        Purpose: This program reads radius and height
        of a cylinder and outputs its area and volume.
    import math
    print "Computing area and volume of a cylinder"
    radius = float( raw_input("Enter radius ==> ") )
    height = float( raw_input("Enter height ==> ") )
    area = 2*math.pi*radius*height + 2*math.pi*radius**2
    volume = math.pi*radius**2*height
    print "Area is: %.2f" %area
    print "Volume is: %.2f" %volume


  • Functions encapsulate a specific operation, which makes it possible to use them for more complex computation.

  • Also, once a function is written and tested, it can be used in many different programs and multiple times in the same program. This simplifies program logic.

  • Functions in modules can be used in many different program.

  • After they are imported, the functions in a module can be executed by a call of the form:

  • You can see the details of a function by:

    >>> help(module_name.function_name)
  • Python has many modules that make it very easy to do many complicated tasks. If you do not believe it, try typing:

    >>> import antigravity