How do I create my own module?

0104

To create your own Python module, follow these steps:

  1. Create a Python file: Create a new file with a .py extension. For example, you can name it my_module.py.

  2. Define functions or classes: Inside this file, you can define functions, classes, or variables. For example:

    # my_module.py
    
    def say_hello():
        print("Hello from my_module!")
    
    def add(a, b):
        return a + b
  3. Save the file: Make sure to save the file in a directory where you can access it from your main Python script.

  4. Import the module: In your main Python script, you can import your module using the import statement:

    import my_module
    
    my_module.say_hello()  # Output: Hello from my_module!
    result = my_module.add(5, 3)
    print(result)  # Output: 8

That's it! You've successfully created and used your own Python module.

0 Comments

no data
Be the first to share your comment!