Section 06: Modules Flashcards

Lesson 08

1
Q

What is Modules?

A

File containing definitions and statements

  • Every .py file is a module
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Math Modules

What are the different ways to call it?

A

(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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the function of the import function?

A
  • Import module: all code inside module is executed
  • If contains statements → execute during import

therefore If, say printstatement in import, then statement is displayed upon import

Sometimes want some code to always execute → other only on certain times: _name_and _main_

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the function of \_\_name\_\_ and \_\_main\_\_ when importing a module?

A

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

  1. When executing the module as the main program then variables _name_ for module set: “_main_
  2. 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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

If there’s a code we like to see executed only when module is the main program:

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly