Python Interview > How can you create a module in python? > Flashcards
general summary
You can create a Python module through one of two methods:
\_\_init\_\_, for it to act as a module.Module Definition and usage
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 / yYou can use math_operations module by using import as shown below:
from math_operations import add result = add(3, 2) print(result)
Best Practice
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.