Lecture

Enhancing Code Reusability and Efficiency with Modules

When coding, you may find yourself writing the same code multiple times to perform specific tasks.

While functions can help reduce repetition, the code may still become lengthy and difficult to manage as the program scales.

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 loads the math module for use in your program.

Example of importing a Python 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 functionality for interacting with the operating system and 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.

Displaying current date and time using the datetime module
# 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 following code uses the random module to generate a random number between 1 and 10.

Generating a random number using the random module
# 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)
Quiz
0 / 1

In Python, a module refers to a file with a specific purpose that collects various variables and functions.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result