Lecture 4 — Using functions and modules

Reading

  • 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 modules, including modules that you write.
  • We will revisit all these concepts in later lectures.

What have we learned so far?

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

  • We also learned some valuable functions that operate on strings

    (len) and that convert between data types (int, str)

    >>> name = "Neil Degrasse Tyson"
    >>> len(name)
    19
    >>> (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
    
  • The functions that Python provides are called built-in functions.

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

String Functions

  • We will learn about many other interesting and useful string functions throughout the semester.

  • Here are a few more string functions:

    >>> name = "Neil Degrasse Tyson"
    >>> name.lower()
    'neil degrasse tyson'
    >>> lowername = name.lower()
    >>> lowername.upper()
    'NEIL DEGRASSE TYSON'
    >>> lowername.capitalize()
    'Neil degrasse tyson'
    >>> lowername.title()
    'Neil Degrasse Tyson'
    >>> "abracadabra".replace("br", "dr")
    'adracadadra'
    >>> "abracadabra".replace("a", "")
    'brcdbr'
    >>> "Neil Degrasse Tyson".find(" ")
    4
    >>> "Neil Degrasse Tyson".find("a")
    9
    >>> "Neil Degrasse Tyson".find("x")
    -1
    >>> "Monty Python".count("o")
    2
    >>> "aaabbbfsassassaaaa".strip("a")
    'bbbfsassass'
    
  • 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)
    11
    >>> episode + "!"
    'Cheese Shop!'
    
  • Be careful, none of these functions change the variable that they are applied to.

Exercise Set 1

  1. Write code that takes a string in a variable called phrase and prints the string with all vowels removed.

  2. 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'
    
  3. Given a string in a variable called name, switch all letters a and e (only lowercase versions). Assume the variable contains only letters and spaces.

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

    >>> name = "Rensselaer Polytechnic Institute"
    ## your code goes here
    
    
    
    >>> name
    'Ranssalear Polytachnic Instituta'
    
  4. Suppose you are given a string with only letters and spaces. 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
    ``'#BringBackTheSwarm'``
    

How about numerical functions

  • Many numerical functions also exist. Let us experiment with some of these first. You should make a note of what they do.

    • abs()
    • pow()
    • int()
    • float()
    • round()
    • max()
    • min()

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:

    • Each object defines an 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:

    variable.function(arguments)
    

    For example:

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

    It also works by:

    value.function(arguments)
    

    as in

    >>> '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

  • Modules are collections 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. When we installed software in Lab 0, we installed a number of external modules, such as PIL for images that we will use 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)
    2.2360679774997898
    >>> math.trunc(4.5)
    4
    >>> math.ceil(4.5)
    5.0
    >>> math.log(1024,2)
    10.0
    >>> math.pi
    3.1415926535897931
    
  • 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 what syntax you need to use the contents of the module in your program.

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

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

    >>> import math as m
    >>> m.pi
    3.141592653589793
    >>> m.sqrt(4)
    2.0
    
  • 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. Since this leads to confusion when the same name appears in two different modules it is almost always avoided.

Program Structure

  • We have now seen several components of a program: import, comments, and our own code, including input, computation and output statements. We will add more components, such as our own functions, as we proceed through the semester.

  • You should organize these components in your program files to make it easy to see the flow of program

  • We will use the following convention to order the program components:

    • an initial comment explaining the purpose of the program,
    • all import statements,
    • then all variables and input commands,
    • then all computation,
    • finally all output.
  • 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
    

Summary

  • Python provides many functions that perform useful operations on strings, integers and floats.

  • Some of these functions are builtin while others are organized into modules

  • After a module is imported, the functions in the module can be used by a call of the form:

    module_name.function_name(arguments)
    
  • You can see the details of a function by:

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

    >>> import antigravity