Junior — Middle
Can you explain what a module in Python is and how it is used to organize code?
sobes.tech AI
Answer from AI
In Python, a module is a file with a .py extension that contains definitions of functions, classes, and variables, as well as executable code. Modules are used to organize and structure code to make it more readable, reusable, and maintainable.
Using modules allows breaking down a program into logical parts. To access the contents of a module in another file, the import statement is used.
Example:
File math_utils.py:
def add(a, b):
return a + b
PI = 3.14159
In another file, you can import and use this module:
import math_utils
result = math_utils.add(2, 3)
print(result) # Outputs 5
print(math_utils.PI) # Outputs 3.14159
Thus, modules help structure code, avoid repetitions, and manage namespace.