Module & statements

Modules in Python are separate files that contain reusable code, including variables, functions, and classes. They allow you to organize your code into separate files, making it more modular, maintainable, and easy to understand. The "import" statement is used to access and use code from these modules in your current script or program.

A module is simply a Python script saved with a "".py" extension. For example, you can create a module named "my_module.py":

# my_module.py
def greet(name):
    print(f"Hello, {name}!")

def square(n):
    return n * n

To use the functions or classes defined in a module, you need to import it into your script or program using the "import" statement.

# main.py
import my_module

my_module.greet("Alice")  # Output: "Hello, Alice!"
result = my_module.square(5)
print(result)  # Output: 25

You can also use the "as" keyword to provide an alias for the module to make the code more concise:

import my_module as mm

mm.greet("Bob")  # Output: "Hello, Bob!"

If you only need specific functions, classes, or variables from a module, you can import them directly:

from my_module import greet, square

greet("Charlie")  # Output: "Hello, Charlie!"
result = square(3)
print(result)  # Output: 9

When a Python script is executed, the special variable "__name__" is set to "'__main__'". You can use this to determine if a module is being run as the main program or being imported into another module.

# my_module.py
def main():
    print("Hello from my_module!")

if __name__ == "__main__":
    main()

When running "my_module.py" directly, the "main()" function will be executed. When importing "my_module" into another script, the code under 'if __name__ == "__main__":' will not be executed.

Modules and the "import" statement provide a powerful way to organize your code, encourage code reuse, and make your projects more modular. They are a cornerstone of Python's modularity and contribute to the readability and maintainability of your code.