Go to: Na-Rae Han's home page  

Python 2.7 Tutorial

With Videos by mybringback.com

#12: Importing Modules

                          << Previous Tutorial           Next Tutorial >>
On this page: import, the time module, time.time(), time.localtime(), time.asctime, the math module, math.sqrt(), math.pow().

Get Started

Video Summary

  • Interactive shell session shown in this tutorial.
  • Use the import function to import modules that are not included within the base Python environment. To begin the import, type import followed by the name of the module.
  • To call a function from an imported module, type the module name, a period, followed by the function name. The most basic function of the time module happens to have the same name as the module itself: the syntax for calling it therefore is time.time(). It returns the number of seconds that have passed since 01/01/1970.
  • Adding more functions to the time() module will produce a time and date in a more-readable format. time.localtime(time.time()) divides that number of seconds returned by the original time function into an actual date with 24 hour timestamp, though it is still messy and difficult to read. Expanding on this, time.asctime(time.localtime(time.time())) takes what is returned by the localtime function and displays it in a legible, standard American date/time format, such as 'Sat Nov 16 12:34:19 2013'.

Learn More

  • That time module sure is complicated! Let's take a look at something simpler: math. First, import it and see what functions are available in it using dir():
     
    >>> import math
    >>> dir(math)
    ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 
    'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 
    'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 
    'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 
    'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
    >>>  
    
  • Some of them look familiar. Let's try .sqrt() 'square root' and .pow() 'power'. .sqrt() is straightforward. How .pow() works is less clear, so we call the help() function on it first to display more information.
     
    >>> math.sqrt(256)
    16.0
    >>> help(math.pow)
    Help on built-in function pow in module math:
    
    pow(...)
        pow(x, y)
        
        Return x**y (x to the power of y).
    	
    >>> math.pow(10,3)
    1000.0
    >>> 
    

Explore