import math
12) math.sqrt(
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 math
In 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
12) math.sqrt(
3.4641016151377544
2.5) math.floor(
2
Here’s an example using the Random module.
import random
random.random()
0.602481588733838
1, 100) random.randint(
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, random
Or one import per line:
import math
import random
It 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 random
Here’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 sqrt
99) sqrt(
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 SquareRoot
65000) SquareRoot(
254.95097567963924