Robotics & Artificial Intelligence

How does a module helps in code reusability? Explain with the help of an example. Create a Python package and one module under it. Write a Python code to use this package.

Python Modules

2 Likes

Answer

A module helps in code reusability by allowing programmers to write commonly used functions and variables once and reuse them in different programs. Instead of writing the same code repeatedly, it can be stored in a module and imported whenever required. This reduces duplication of code, makes programs simpler, and improves organisation.

Example:

Package structure:

my_new_package/
    my_module.py
main.py

Create the module: my_new_package/my_module.py

# my_module.py

school_name = "KnowledgeBoat"

def greet_student(name):
    return f"Hello {name}! Welcome to {school_name}."

Use this package in a program: main.py

# main.py

from my_new_package.my_module import school_name, greet_student

print("School:", school_name)
print(greet_student("Aarav"))

Output (sample):

School: KnowledgeBoat
Hello Aarav! Welcome to KnowledgeBoat.

Answered By

3 Likes


Related Questions