Contents
What are Python Modules?
Python modules are files containing Python code that can define features, instructions, and variables. They provide a way to arrange code into reusable components, promoting modularity and code reusability. Modules let you cut up your application into more than one files, every that specialize in a particular component of capability.
Example
import math
# Calculate and print the square root of 100
print(“Square root of 100:”, math.sqrt(100))
Output
Square root of 100: 10.0
-
Creating Modules:
To create a module, you in reality write Python code in a .py document. each .py record acts as a separate module, and its filename (with out the .py extension) serves as the module call. here’s an example of a simple module named mymodule.py:
Example mymodule.py
# Contents of mymodule.py
def greet(name):
print(f”Hello, {name}!”)
-
Importing Modules:
Once you have created a module, you can import it into different Python scripts or interactive classes using the import assertion. This offers you get admission to to the capabilities, training, and variables described in the module. here’s how you import the greet feature from the mymodule module:
Example main.py
# Importing the greet function from the mymodule module
from mymodule import greet
# Using the greet function
greet(“Ramkrishna Kumar”)
Output:
Hello, Ramkrishna Kumar!
-
Module Namespace:
When you import a module, you create a brand new namespace containing all the names defined in that module. To get admission to those names, you want to prefix them with the module name followed through a dot (.). This helps keep away from naming conflicts and lets in for higher code company.
Example main.py
# Importing the entire module
import mymodule
# Using the greet function from the mymodule module
mymodule.greet(“Rohan Kumar”)
Output:
Hello, Rohan Kumar!
-
Standard Library Modules:
Python comes with a well known library that includes many modules providing various functionalities such as report I/O, networking, and records processing. these modules are effectively available for use while not having to install any additional programs.
here’s an instance of uploading and using the math module from the standard library:
Example
# Importing the math module
import math
# Using the pi constant from the math module
print(“Value of pi:”, math.pi)
Output:
Value of pi: 3.141592653589793