Alex had been studying Python for a while now and had become quite familiar with the core language features. He had also learned about functions, classes, and objects, and how to work with them. But as his Python programs grew larger and more complex, he started to realize the importance of organizing his code into reusable components.
That’s when he discovered Python modules. A module is simply a file containing Python definitions and statements. The file name is the module name with the .py
extension. Modules can contain functions, classes, and variables that can be used in other programs by importing them.
To understand modules better, Alex decided to create a simple module that contained some useful functions. He created a file called my_module.py
and defined two functions inside it.
# my_module.py def square(x): return x ** 2 def cube(x): return x ** 3
Next, Alex created another Python file called my_program.py
and imported the functions from my_module.py
.
# my_program.py import my_module print(my_module.square(5)) print(my_module.cube(3))
The output was:
25 27
Alex was able to see that he could use the functions defined in my_module.py
in my_program.py
. He could also use the as
keyword to give the imported module a different name, like this:
import my_module as mm print(mm.square(5)) print(mm.cube(3))
The output was the same as before:
25 27
Alex also learned that he could import specific functions or variables from a module using the from
keyword.
from my_module import square print(square(5))
The output was:
25
Finally, Alex learned that Python had a number of built-in modules that he could use in his programs, such as math
, random
, datetime
, and many others. He could also install and use third-party modules that were not included in the Python standard library.
With modules, Alex realized he could write more efficient and organized code, and he felt empowered to tackle even more complex programming challenges.