Modules in Python

Modules in Python are files that contain Python code, which can be imported and used in other Python scripts. Modules are useful for organizing and reusing code, as well as for sharing code between different projects.

Python comes with a standard library of modules that provide a wide range of functionality, such as working with files, performing mathematical operations, and interacting with the internet. Additionally, there are many third-party modules available that can be installed and used in Python.

Here is an example of how to import and use a module in Python:

python
# Import a module
import math

# Use a function from the module
x = math.sqrt(25)

print(x)  # Output: 5.0

In this example, the `math` module is imported using the `import` keyword. The `sqrt()` function from the `math` module is then used to calculate the square root of `25`, which is assigned to the variable `x`. Finally, the value of `x` is printed to the console.

You can also import specific functions or variables from a module using the `from` keyword:

python
# Import a specific function from a module
from math import sqrt

# Use the imported function
x = sqrt(25)

print(x)  # Output: 5.0

In this example, only the `sqrt()` function is imported from the `math` module using the `from` keyword. The function can then be used without referencing the module name.

You can also create your own modules by writing Python code in a file with a `.py` extension. To use the functions and variables defined in your module, you can import them into another Python script using the `import` keyword.

python
# Define a function in a module
# File: mymodule.py
def greet(name):
    print("Hello, " + name + "!")

# Use the function from the module
import mymodule

mymodule.greet("Alice")  # Output: "Hello, Alice!"

In this example, the `greet()` function is defined in a file called `mymodule.py`. The function is then imported into another Python script using the `import` keyword, and the function is called with the argument “Alice”.