CoachFullStack

Python Guide #10: Importing Modules

Python’s power is in its modules. So far we have been using only standard operations provided by Python itself. However, there is a lot of modules available in standard Python library, as well as available to install using pip, which is a Python package manager. You can also download modules from the interner, or even write them yourself.

This time we will focus on importing modules, that are present within Python standard library and show how to install modules using pip.

# you can import whole module
import module
# or just a piece of it
from module import component

Example:

# We will use python
# random module to
# choose random element
# from a list

import random
names = [
    "John",
    "Bob",
    "Alice",
    "Tom",
    "Harry"
]

print(random.choice(names))

Inside of a random module, there is a function choice() which we access using module name followed by a dot. This works for both objects and functions within modules and objects.

You can access mathods of different objects.

We will use string as an example:

e = ["a", "b", "c"]
new_e = " | ".join(e)
print(new_e)

Execute program above to see what happens.

Installing modules using pip

If you want to install new package, open command line and execute command

# on linux
pip3 install package_name
# on windows
pip install package_name

Available packages are listed on pypi.org.



Next: Python Guide #11: Reading Files

Previous: Python Guide #9: User Input