w3resource

What are modules in Python, and how do they organize code?

Python modules: Enhancing code organization and reusability

A Python module is a file containing Python code that defines variables, functions, and classes. In modules, code is organized into logical units, making it easier to reuse code across different parts of a program or across multiple programs.

Python modules serve several purposes:

  • Code Organization: Modules make it easier to break down a large program into smaller, more manageable parts. You can import and use each module to handle specific functions.
  • Code Reusability: Modules can be imported and used in other Python programs once they have been defined. This helps in writing DRY (Don't Repeat Yourself) code.
  • Encapsulation: Modules provide a level of encapsulation, where internal details of a module can be hidden from other parts of the program, which promotes clean, maintainable code.
  • Namespace: Each module defines its own namespace, preventing naming conflicts with other modules.
  • To create a module, you define your Python code in a .py file. For example, if you create a file named test_module.py containing some functions, classes, or variables, you can import and use those in other parts of your program using the import statement.

Example: Python module

Code:

#test_module.py
# Define a function to check if a number is even
def is_even(x):
    return x % 2 == 0
# Define a function to check if a number is odd
def is_odd(x):
    return x % 2 != 0
# Variable to store a constant value
PI = 3.14159

You can now use the functions and variable defined in test_module.py in another Python script:

Code:

import test_module
# Using functions from the module
print("Is 7 is even? ",test_module.is_even(7))
print("Is 8 is even? ",test_module.is_even(8))
print("\nIs 3 is odd? ",test_module.is_odd(3))
print("Is 10 is odd? ",test_module.is_odd(10))
# Using the variable from the module
print("\nValue of PI:", test_module.PI)

Output:

Is 7 is even?  False
Is 8 is even?  True

Is 3 is odd?  True
Is 10 is odd?  False

Value of PI: 3.14159

In the above example , the code in main.py imports the test_module module and uses the functions is_even() and is_odd() as well as the constant PI defined in the module.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-interview/what-are-modules-in-python-and-how-do-they-organize-code.php