Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Modules - LangChain

What is a Module?

A module is a file containing Python definitions and statements. Modules allow you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. It also makes the code reusable.

Creating a Module

Creating a module in Python is simple. Just save your code with a .py extension. For example, let's create a module named mymodule.py:

mymodule.py
def greet(name):
    return f"Hello, {name}!"

Using a Module

To use the module, you need to import it using the import statement. Here's how you can use the mymodule.py we created:

main.py
import mymodule

name = "World"
print(mymodule.greet(name))

Output:

Hello, World!

Built-in Modules

Python comes with a standard library of modules. You can use these modules to perform various tasks. For example, the math module provides mathematical functions:

math_example.py
import math

result = math.sqrt(16)
print(result)

Output:

4.0

Installing External Modules

You can install external modules using the Python package manager pip. For example, to install the requests module, you can use the following command:

pip install requests

After installing, you can use the module in your code:

requests_example.py
import requests

response = requests.get('https://api.github.com')
print(response.status_code)

Output:

200

Conclusion

Modules are a powerful feature in Python that helps you organize your code, make it reusable, and leverage existing libraries. Whether you're using built-in modules, creating your own, or installing external ones, modules will significantly enhance your Python programming capabilities.