Generic Imports
Generic Imports
Did you see that? Python said: NameError: name 'sqrt' is not defined. Python
doesn’t know what square roots are—yet.
There is a Python module named math that includes a number of useful variables and
functions, and sqrt() is one of those functions. In order to access math, all you
need is the import keyword. When you simply import a module this way, it’s called a
generic import.
Instructions
Checkpoint 1 Enabled
1.
You’ll need to do two things here:
code
mport math
print math.sqrt(25)
Function Imports
Nice work! Now Python knows how to take the square root of a number.
However, we only really needed the sqrt function, and it can be frustrating to have
to keep typing math.sqrt().
It’s possible to import only certain variables or functions from a given module.
Pulling in just a single function from a module is called a function import, and
it’s done with the from keyword:
Now you can just type sqrt() to get the square root of a number—no more
math.sqrt()!
Instructions
Checkpoint 1 Enabled
1.
Let’s import only the sqrt function from math this time. (You don’t need the ()
after sqrt in the from math import sqrt bit.)
Instructions
Checkpoint 1 Passed
1.
Use the power of from module import * to import everything from the math module on
line 3 of the editor.
code
from math import *
Instructions
Checkpoint 1 Enabled
1.
The code in the editor will show you everything available in the math module.
Click Run to check it out (you’ll see sqrt, along with some other useful things
like pi, factorial, and trigonometric functions.
code
import math # Imports the math module
everything = dir(math) # Sets everything to a list of things from math
print everything # Prints 'em all!