Execute Program

Python for Programmers: Importing and the Standard Library

Welcome to the Importing and the Standard Library lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • We've seen built-in functions like len and built-in data types like dict. These are always available globally. Python also has a rich standard library, which is a set of modules providing functionality beyond core language features.

  • For example, the standard library has a math module that exports a sqrt (square root) function. We can import math to get access to the module, then call math.sqrt.

  • >
    import math

    math.sqrt(25.0)
    Result:
    5.0Pass Icon
  • Modules can export any value, not just functions. For example, math exports the constant pi.

  • >
    import math

    math.pi
    Result:
  • math also exports a ceil function (ceiling), which rounds a number up to the closest integer.

  • >
    import math

    math.ceil(math.pi)
    Result:
    4Pass Icon
  • Sometimes we use an imported function many times. To keep those calls short, we might want to call ceil(...) instead of math.ceil(...). If we only imported as import math, then accessing ceil is a NameError. (You can type error when a code example will cause an error.)

  • >
    import math

    sqrt(25.0)
    Result:
    NameError: name 'sqrt' is not definedPass Icon
  • We could assign the function to a name, then call it that way.

  • >
    import math

    sqrt = math.sqrt
    sqrt(25.0)
    Result:
    5.0Pass Icon
  • However, it's better to use a "qualified import", like from math import sqrt. Each imported name is available in the namespace, without requiring the math. prefix.

  • >
    from math import sqrt

    sqrt(25.0)
    Result:
    5.0Pass Icon
  • Qualified imports can import multiple names at once. We separate them with commas, like from some_module import name_1, name_2.

  • >
    from math import ceil, pi

    ceil(pi)
    Result:
    4Pass Icon
  • We can use as to use a different name for our imports. It works on imported modules and on qualified imports.

  • >
    import math as m

    m.sqrt(25.0)
    Result:
    5.0Pass Icon
  • >
    from math import ceil as ceiling, pi as PI

    ceiling(PI)
    Result:
    4Pass Icon
  • This can be useful to avoid naming conflicts, or to give imports shorter names.

  • For example, pandas is a common data science library in Python. Instead of qualified imports, most pandas code starts with import pandas as pd. That lets us refer to the functions quickly, like pd.read_csv. The pd. makes it clear that they came from pandas.