w1coding.comAll tutorials

Python Libray

Python lessons
  1. Environment Setup
  2. Introduction
  3. Control
  4. Control
  5. Loops
  6. Functions
  7. Lists
  8. Dictionary
  9. Classes
  10. Exception
  11. File
  12. Libray
  13. Date
  14. Regula
  15. JSON
  16. Web
  17. Zweb
  18. Apis
  19. Unity
  20. Llampda
  21. Iterators
  22. Generators
  23. Files
  24. Context
  25. Ilogging
  26. Multithreading
  27. Networking
  28. SQLite

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.