Enhancing Code Reusability and Efficiency with Modules
When coding, you may find yourself writing the same code multiple times to perform specific tasks.
Functions help solve this problem to some extent, but as the program grows, the code becomes lengthy and challenging to maintain.
In Python, this issue can be resolved by using modules
.
A module is a separate, standalone Python file that groups together variables, constants, functions, etc., for a specific purpose.
For example, if you create a module for frequently used mathematical operations and string processing functions, you can import and utilize this module in other Python programs.
What is the difference between a module and a library?
A library
is a collection of multiple modules.
A single module is one Python file, while a library is a collection of several modules (i.e., several Python files).
For instance, the math
module is one of the standard libraries provided with Python, offering functions for mathematical operations.
How do you use a Python module?
Python imports a module using the import
keyword.
In the code below, import math
imports the math module.
# Import the math module for mathematical operations
import math
# Use the sqrt function from the math module
result = math.sqrt(16)
# Outputs 4.0
print(result)
You can use functions defined in a module with the syntax module_name.function_name
.
In the example above, the sqrt
function from the math module calculates the square root, and math.sqrt(16)
returns 4.0, the square root of 16.
Utilizing Python Standard Libraries
In addition to math, Python provides various modules such as os (operating system), datetime (dates and times), and random (random numbers).
-
os
: Provides functionalities for interacting with the operating system and handling the file system -
datetime
: Offers various functions for working with dates and times -
random
: Provides functionalities related to random number generation
The following code uses the now
function from the datetime
module to get the current date and time.
# Import the datetime module
import datetime
# Get the current date and time
current_time = datetime.datetime.now()
# Print the current time
print(current_time)
# Example output: 2024-08-25 15:30:00.123456
The below code uses the random
module to generate a random number between 1 and 10.
# Import the random module
import random
# Generate a random number between 1 and 10
random_number = random.randint(1, 10)
# Print the generated random number
print(random_number)
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.