A module lets you write functions once and use them in any number of programs. You have already imported built-in modules such as os and shutil; here you create your own.
What a module is
Any .py file is a module. Grouping related functions, classes and variables in one module makes them reusable, avoids copying code between programs, and gives each module its own namespace: names inside series.py do not clash with the same names in another file, because they are reached as series.name.
The three ways to import
Form
Example
How names are used
Best for
Whole module
import math
math.sqrt(16), math.pi
Most cases; clear where names come from
Whole module with alias
import statistics as st
st.mean(data)
Long module names
Selected names
from math import pi, sqrt
pi, sqrt(16) directly; math.pi is a NameError
A few frequently used names
All public names
from math import *
sqrt(16), log(2) directly
Interactive experiments only
from module import * imports every public name (names not starting with _), or exactly the names listed in the module’s __all__ if it defines one. It can silently overwrite your own names, so PEP 8 advises against it in programs.
What happens on import
Python finds the file using the module search path (next section).
It compiles the module to bytecode and, for later runs, caches the result as a .pyc file in a __pycache__ folder, so the module loads faster next time (the code itself runs at the same speed).
It runs the module’s top-level code from top to bottom once, creating its functions and variables.
It binds the module name in the importing file. A second import of the same module in the same program reuses the loaded module without running it again.
Key takeaways
A module is a .py file; its name is the file name.
import m, import m as x, from m import a, b, from m import *.
Each module has its own namespace.
A module runs once per program; bytecode is cached in __pycache__.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Explain why from module import * is discouraged in programs, with an example.
Show worked answer
It copies every public name of the module into your namespace without listing them, so a reader cannot see where a name came from, and names can be silently overwritten. For example, after def pow(a, b): ... in your file, a later from math import * replaces your pow with math.pow, which always returns a float. Writing import math and using math.pow, or importing the needed names explicitly, avoids both problems.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/modules-and-packages/creating-and-using-modules/ to read this page.