[go: up one dir, main page]

0% found this document useful (0 votes)
4 views2 pages

Generic Imports

Uploaded by

knadx619
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Generic Imports

Uploaded by

knadx619
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

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:

Type import math on line 2 in the editor.


Insert math. before sqrt() so that it has the form math.sqrt(). This tells Python
not only to import math, but to get the sqrt() function from within math. Then hit
Run to see what Python now knows.

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:

from module import function

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!

You might also like