Functions and Modules 🧩: Organizing Python Code
Functions in Python help encapsulate code into reusable blocks, improving readability and maintainability.
Defining Functions:
def greet(name):
return f'Hello, {name}!'
print(greet('Alice'))
Functions can accept parameters and return values.
Modules:
Python files (.py
) can be imported as modules to share code.
# In my_module.py
def add(a, b):
return a + b
# In main script
import my_module
result = my_module.add(3, 4)
print(result) # Output: 7
Modules promote code reuse and organization, especially in larger projects.
Built-in Modules:
Python provides modules like math
, datetime
, os
, etc., to perform common tasks.
import math
print(math.sqrt(16)) # Output: 4.0
Mastering functions and modules accelerates development and encourages clean, modular code.