A module is a file of Python code that someone else wrote, full of
functions and values you can use. The import statement pulls a
module into your script so you can reach what's inside it. Python
ships with hundreds of modules, and this is how you get at them.
The plain form loads a module and gives you access through its name:
import os
print(os.getcwd())
After import os, everything the os module provides is available
under the os. prefix. os.getcwd() calls the getcwd function that
lives inside os. The prefix makes it obvious where the function came
from, which helps when a script imports several modules.
When you only want one or two things from a module, import them directly so you can use them without the prefix:
from os import getcwd
print(getcwd())
Now getcwd is available on its own. This reads well when you use a
name often, but too many bare imports make it hard to tell which
module each one came from.
as renames what you import, usually to shorten a long module name or
avoid a clash:
import subprocess as sp
sp.run(["ls"])
You'll see this constantly in real code, where libraries have a conventional short alias.
Put imports at the top of your script, before any other code. Python runs them once, and every function below can use what they brought in.
import module loads a module, used through the module. prefix.from module import name pulls one name in without the prefix.import module as alias renames it.