1. Functions
Functions are reusable blocks of code that perform specific tasks. They allow you to write once and reuse multiple times, reducing redundancy and making your code easier to maintain.
Syntax:
def function_name(parameters): # Code block return value
Example:
def greet(name): print(f"Hello, {name}!") # Calling the function greet("Alice")
Key Points:
- Parameters and Arguments:
- Parameters are variables defined in the function declaration (e.g.,
name
). - Arguments are values passed to the function (e.g.,
"Alice"
).
- Parameters are variables defined in the function declaration (e.g.,
- Default Parameters:
- Return Statement:
- Docstrings: Always document your functions for clarity.
def greet(name="User"): print(f"Hello, {name}!") greet() # Output: Hello, User!
def add(a, b): return a + b result = add(5, 3) print(result) # Output: 8
def greet(name): """Greets the user by name.""" print(f"Hello, {name}!")
2. Modules
Modules are Python files containing a collection of functions, classes, and variables. They help organize your code into separate files, making it more modular and easier to manage.
Importing Modules:
Use the import
statement to include modules in your script.
Example:
Create a module named math_tools.py
:
# math_tools.py def add(a, b): return a + b def subtract(a, b): return a - b
Use it in another script:
# main.py import math_tools result = math_tools.add(10, 5) print(result) # Output: 15
3. Packages
Packages are collections of modules organized in directories with a special __init__.py file. They allow you to structure your projects into logical components.
Creating a Package:
- Directory Structure:
- Example Files:
- module1.py
- module2.py
- Using the Package:
Functions encapsulate logic and promote reusability.
Modules organize code into manageable files.
Packages structure projects into logical components.
Use tools like
pip
to install and manage external packages for added functionality.
# main.py my_package/ __init__.py module1.py module2.py
def greet(): print("Hello from Module 1!")
def farewell(): print("Goodbye from Module 2!")
from my_package import module1, module2 module1.greet() # Output: Hello from Module 1! module2.farewell() # Output: Goodbye from Module 2!
Installing External Packages:
Use pip
to install third-party packages from the Python Package Index (PyPI).
Example:
pip install requests
Using the installed package:
import requests response = requests.get("https://api.github.com") print(response.status_code)
4. Combining Functions, Modules, and Packages
By combining these concepts, you can create well-organized, professional projects.
Example Project Structure:
password_manager/ __init__.py password_generator.py password_validator.py main.py
password_generator.py:
import random def generate_password(length=8): chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()" return ''.join(random.choice(chars) for _ in range(length))
password_validator.py:
def validate_password(password): if len(password) < 8: return "Password too short!" if not any(char.isdigit() for char in password): return "Password must contain a number!" if not any(char.isupper() for char in password): return "Password must contain an uppercase letter!" return "Password is valid."
main.py:
from password_manager.password_generator import generate_password from password_manager.password_validator import validate_password password = generate_password(12) print(f"Generated Password: {password}") validation = validate_password(password) print(validation)
Run main.py to see the result:
python main.py
5. Key Takeaways
By mastering these concepts, you’ll be able to write clean, efficient, and maintainable Python scripts that scale easily as your projects grow.
Comments
Post a Comment