import statement

  • Import options for numpy:
    import numpy as np            # Access as np.functionName (USE THIS)
    import numpy                  # Access as numpy.functionName
    import numpy as numnum        # Access as numnum.functionName
    from   numpy import sin, cos  # Access as x=cos(5) or x=sin(5)
    from   numpy import *         # Access as functionName (NEVER DO THIS)


  • You can save code in other files ( and load it into python like you have been doing with libraries.

Create a code file

  • Jupyter's home screen --> New --> text file
  • Save the file as "" at the top
  • Edit the file to have the following code, then save it:
ft_to_m = 1.0/3.28084
m_to_ft = 3.28084
lbm_to_kg = 1.0/2.20462
kg_to_lbm = 2.20462

def K_to_C(T_K):
    return T_K - 278.15
def F_to_C(T_F):
    return (T_F - 32.0)/1.8

Now you can import this file and its variables/functions

In [2]:
import units as u

x_ft = 10
x_m  = x_ft * u.ft_to_m

T = 212  # F
TC = u.F_to_C(T)

Load certain variables or functions from the module directly

In [6]:
from units import F_to_C


The code in the module is run when the module is loaded

  • This allows you to hide boilerplate code in a module and simply import the module.
  • For example, here is the contents of a file called

    import numpy as np
    import matplotlib.pyplot as plt
    import sympy as sp
    import glob
  • Now load all of these modules with a simple

from all_imports import *
In [4]:
from all_imports import *

The module you load has to be in the same directory

  • If not, it will search for the modules in directories specified in a system variable PYTHONPATH which you can edit.
  • You can also add the path in python:
    import sys

dir() function

  • The dir(u) function will show a list of names that module u defines
  • dir(u) will show all currently known names (except builtin names)
In [4]:
In [ ]: