Skip to main content

Python Tutorial 6.2 - Creating Modules in Python

Welcome to the “Creating Modules” tutorial!


Overview

Modules are Python files (.py) that group related code. You can import them elsewhere.

Steps

  1. Create a file mymodule.py:

    # mymodule.py
    def greet(name):
        return f"Hello, {name}!"
    
  2. Import and use in another script:

    # main.py
    import mymodule
    print(mymodule.greet("Alice"))
    
  3. Use aliases:

    from mymodule import greet as hello
    print(hello("Bob"))
    

Key Takeaways

  • Organize reusable functions and classes into modules.
  • Use import module or from module import name as needed.

Happy coding!

Comments