How can you create a module in python? Flashcards

(4 cards)

1
Q

general summary

A

You can create a Python module through one of two methods:

  • Define: Begin with saving a Python file with .py extension. This file will automatically function as a module.
  • Create a Blank Module: Start an empty file with no extension. Name the file using the accepted module syntax, e.g.,\_\_init\_\_, for it to act as a module.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Module Definition and usage

A

Save the below math_operations.py file

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    return x / y

You can use math_operations module by using import as shown below:

from math_operations import add

result = add(3, 2)
print(result)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Best Practice

A

Avoid Global Variables: Use a main() function.

Guard Against Code Execution on Import: To avoid unintended side effects, use:

if \_\_name\_\_ == "\_\_main\_\_":
    main()

This makes sure that the block of code following if __name__ == “__main__”: is only executed when the module is run directly and not when imported as a module in another program.

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