Importing Modules [Python]
All Python programs can call a basic set of functions called built-in functions, including the print(), input(), and len() functions you’ve seen before. Python also comes with a set of modules called the standard library. Each module is a Python program that contains a related group of functions that can be embedded in your programs. For example, the math module has mathematicsrelated functions, the random module has random number–related functions, and so on.
Before you can use the functions in a module, you must import the module with an import statement. In code, an import statement consists of the following:
Once you import a module, you can use all the cool functions of that module. Let’s give it a try with the random module, which will give us access to the random.ranint() function.
Enter this code into the file editor, and save it as printRandom.py:
The random.randint() function call evaluates to a random integer value between the two integers that you pass it. Since randint() is in the random module, you must first type random. in front of the function name to tell Python to look for this function inside the random module. Here’s an example of an import statement that imports four different modules:
import random, sys, os, math
Now we can use any of the functions in these four modules. We’ll learn more about them later in the book.
With this form of import statement, calls to functions in random will not need the random. prefix. However, using the full name makes for more readable code, so it is better to use the normal form of the import statement.
Importing Modules [Python] |
Before you can use the functions in a module, you must import the module with an import statement. In code, an import statement consists of the following:
- The import keyword
- The name of the module
- Optionally, more module names, as long as they are separated by commas
Once you import a module, you can use all the cool functions of that module. Let’s give it a try with the random module, which will give us access to the random.ranint() function.
Enter this code into the file editor, and save it as printRandom.py:
Importing Modules [Python] |
import random, sys, os, math
Now we can use any of the functions in these four modules. We’ll learn more about them later in the book.
from import Statements
An alternative form of the import statement is composed of the from keyword, followed by the module name, the import keyword, and a star; for example, from random import *.With this form of import statement, calls to functions in random will not need the random. prefix. However, using the full name makes for more readable code, so it is better to use the normal form of the import statement.
0 Response to "Importing Modules [Python]"
Post a Comment