libray

Python Libraries and Modules

Python Libraries and Modules

Modules are files containing Python code that can be imported into other programs to use the functions and variables defined in them. Libraries are collections of related modules.

Importing a Module

You can import a module using the import keyword:

      
        import math
        print(math.sqrt(16))
      
    

This imports the math module and uses its sqrt() function to calculate the square root of 16.

Creating a Module

You can also create your own modules by saving Python code in a file with the .py extension. For example, if you have a file called my_module.py:

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

You can import and use it in another script:

      
        import my_module
        print(my_module.greet("Alice"))
      
    

Activity

Try It Yourself!

Create a module with a function that multiplies two numbers, then import and use that function in a separate Python file.

Quick Quiz

Quick Quiz

  1. What is the purpose of a Python module?
  2. How do you import a module in Python?

Answers: A Python module contains reusable code that you can import into other programs. You import a module using the import keyword.