Modules
Modules in Python are files containing Python definitions and statements. They allow you to organize and reuse code across different programs.
You can import modules using the import statement.
import module_name
ㅤ
from module_name import function_name
ㅤ
from module_name import *
You can create your own modules by saving Python code in a .py file.
def greet(name):
ㅤㅤreturn f"Hello, {name}!"
ㅤ
def farewell(name):
ㅤㅤreturn f"Goodbye, {name}!"
After importing a module, you can use its functions and variables.
import my_module
ㅤ
print(my_module.greet("Alice"))
print(my_module.farewell("Bob"))
Python comes with many built-in modules that provide additional functionality.
import math
ㅤ
print(math.pi)
print(math.sqrt(16))
The dir() function can be used to find out which names a module defines.
import math
ㅤ
print(dir(math))
Modules are a powerful way to organize and reuse code in Python. They help in maintaining large codebases and promote code reusability.