Python Programming by Example (2015)
6. Python Modules and Packages
This chapter explains how to work Python modules and packages.
6.1 Python Modules
In this chapter, we learn how to access Python modules. A list of Python package can be found this website, https://pypi.python.org/pypi?%3Aaction=index .
6.2 import Statement
You can access Python module using import. Try to write these scripts.
import math
a = math.sin(0.3)
print(a)
b = math.sqrt(math.sin(0.5) * math.pow(5, 3))
print(b)
Save into a file, called ch06_01.py. Run the program.
$ python3 ch06_01.py
Program output:
6.3 from...import * Statement
On previous section, we use import to use Python module. To use it, you should module name. You can ignore it using from...import statement.
Write these scripts.
from math import *
a = sin(0.3)
print(a)
b = sqrt(sin(0.5) * pow(5, 3))
print(b)
You can see we don't need to call math.sin(). We just call sin().
Save and ryn the program.
$ python3 ch06_02.py
Program output:
6.4 Installing External Python Package
If you want to use external Python Package, for instance, Colorama, https://pypi.python.org/pypi/colorama . We can install itu via pip.
Type this command on Terminal.
pip install colorama
If you want to install it for Python 3.x, you should pip3.
pip3 install colorama
Now let's write the demo.
import colorama
from colorama import Fore, Back, Style
colorama.init()
message = "hello world from python"
print(message)
print(Fore.RED + message)
print(Fore.GREEN + message)
print(Fore.BLUE + message)
print(Fore.RED + Back.YELLOW + message + Style.RESET_ALL)
Save into a file, called ch06_03.py.
$ python3 ch06_03.py
Program output: