Section 06: Modules Flashcards
Lesson 08
What is Modules?
File containing definitions and statements
- Every
.py
file is a module
Math Modules
What are the different ways to call it?
(1) Can use the code inside a module from a different file → import module
Call the module by name using dot operator:
```python
x = math.sqrt(w)
~~~
(2) Calling the functions directly → from math import sin, sqrt
Only call the sin
and sqrt
functions:
(3) Call to allow full use of module → from math import*
Use any of the function
However, proceed with causation and not always recommended
(4) Using the dot operator and renaming the module → import math as m
What is the function of the import
function?
- Import module: all code inside module is executed
- If contains statements → execute during import
therefore If, say print
statement in import
, then statement is displayed upon import
Sometimes want some code to always execute → other only on certain times: _name_
and _main_
What is the function of \_\_name\_\_
and \_\_main\_\_
when importing a module?
Variable that the interpreter initializes whenever it executes a module (specific to each module)
When executed:
1. sets the value _name_
2. Executes all the code in module
- When executing the module as the main program then variables
_name_
for module set: “_main_
” - When executing the module as part of an import statement from other module, then
_name_
is set to be equal to name of module (not_main_
)
After var name set → interpreter executes code one statement at time
When running my_module
directly, the value of _name_ == _main_
Then print certain if
statements in module it was created (not imported to)
If there’s a code we like to see executed only when module is the main program: