import math
math.sqrt(12)3.4641016151377544
Programming for Data Science
Previously we saw that we can extend the functions available to use in a Python program by importing them.
For example, we imported the Math module to make its log function available.
import mathIn this notebook, we cover some basic properties of import statements.
We’ll go into greater detail when we cover Modules.
Recall that calling a function from the import math object is straightforward:
For example, to get the square root of \(12\) we can now do this:
import math
math.sqrt(12)3.4641016151377544
math.floor(2.5)2
Here’s an example using the Random module.
import randomrandom.random()0.602481588733838
random.randint(1, 100)8
We call functions from imported modules by object using “dot” notation.
You can import as many modules into your code as you’d like.
We can do this as follows:
import math, randomOr one import per line:
import math
import randomIt is generally preferred to separate import statements by line.
This makes you code more readable and modular.
Regarding modularity, with one import per line, you can do things like this:
import math
# import randomHere’s we quickly comment out an import statement without having to rewrite our code.
It is also a standard practice to put all of your import statements at the very top of your code, before any other code.
If you know what to use a specific function from an imported module, you can import them directly, like so:
from math import sqrtsqrt(99)9.9498743710662
This reduces the memory used by the library in your program, since it is not importing all of the module’s code.
It also allows you to call the function directly, with the object dot notation.
You can alias the imported function.
This avoids having the function name conflict with an existing function in your program.
from math import sqrt as SquareRootSquareRoot(65000)254.95097567963924