Lesson 3
Discovering your Paths
Chapter 7: Using existing functions
Importing modules
Python provides more than the standard built-in functions.
For example, Python provides a math
module containing many common mathematical functions.
A module is a file somewhere on your hard drive that contains a collection of functions and variables (among other things) that are usually related to each other. We will discuss more about modules in future lessons.
To use the functions in a module, you will first have to import the module to your program.
You simply use the import
keyword to do this.
For example, the code below imports the math
module.
>>> import math
This will create a module
object called math
.
>>> math
<module 'math' (built-in)>
>>> type(math)
<class 'module'>
The module object contains the functions and variables as defined in the module.
To access one of these variables or functions, use the name of the module, followed by a dot, and followed by the variable/function name. This is known as “dot notation”.
>>> math.sqrt(9)
3
>>> math.pi
3.141592653589793