Python

Modules and Packages

Modules and packages are an important part of programming in Python. They allow you to reuse code and organize your code into logical units.

A module is a Python file that contains a set of functions, classes, or variables that can be used in other Python programs. For example, the math module contains functions for performing mathematical calculations, such as square roots and trigonometric functions.

A package is a collection of modules. It is similar to a module, but it contains multiple modules and often has a file structure. Packages are used to organise related modules, making it easier to find and use them.

Import

To use a module or package in your code, you must import it. This is done using the import statement. For example, to import the math module, you would use the following code:

import math
Functions and Variables

You can then use the functions and variables from the math module by calling them with the dot notation. For example, to use the square root function from the math module, you would use the following code:

result = math.sqrt(25)
Importing a specific function

You can also import specific functions or variables from a module or package using the from keyword. For example, to import the square root function from the math module, you would use the following code:

from math import sqrt

You can then use the square root function without the dot notation:

result = sqrt(25)
Pip install

Libraries are collections of modules and packages that provide a set of functions and classes for a specific purpose. For example, the NumPy library is a popular library for scientific computing, and the Pygame library is a popular library for creating games.

To use a library, you must first install it. This is typically done using a package manager, such as pip. Once the library is installed, you can import it and use it in your code just like you would a module or package.