Lesson 10 Flashcards
Libraries/modules
A python module is a reusable collection of functions, variables, and code that can be imported into a program to extend its functionality
Modules provide a structured and efficient way to share reusable code with others
Why are modules good
Maintainability: updates and improvements can be made to a module without modifying the main program.
Modularity: Enabling independent development and debugging of different parts of a program
Creating a module:
Write function definitions and variables in a file and save it with the *.py extension
Using a module
There are multiple ways to import a module to gain access to the functions/variables within it.
Importing a module
Import list_processor
import list_processor as lp #alias
from list_processor import sum_all, LIST_OF_ZERO #specific functions/ variables
Importing multiple modules:
in case there are name conflicts with functions/variables imported from multiple modules you should rename them at the time of import
Changing names at import
from another_module import sum_all as sum_all2
Circular imports
When two modules depend on each other
Running a script bs importing a script:
Any *.py file is considered a script but some are intended ti be modules and other programs.
Every python script has a special built in variable called:
__name__
When a script runs directly, __name__ is set to
“__main__”
When a script is imported as a module, __name__
is set to the modules filename
To promote reusability in scripts
it is best practice to separate script logic and library code.
Built in modules:
these come pre installed with python and can be directly imported using the methods introduced
Common built in modules
math- extends the list of mathematical functions
sys- provides access to system specific parameters and functions, allowing interaction with the python runtime environment (sys.argv, e.g.)
os-interact with the operating system (manage files and folders, e.g)
random: make random numbers
datetime: create dates
External modules: these have to be installed
- In a terminal window, type ‘pip install <module>’
Typically pip is pre installed when Python is installed. If it is not, use Google/chatGPT to help you install pip</module>
numpy
Used for working with arrays/matrices
Matplot lib
used for plotting data
Sklearn
machine learning