Explain assertions, raising exceptions, and any functions from the shutil module
1. Assertions in Python
- Used to check if a condition is True during program execution.
- If the condition is False, Python raises an
AssertionError.
Syntax:
assert condition, "error message"
Example:
x = 10 assert x > 0, "x should be positive"
Useful for debugging and testing assumptions in code.
2. Raising Exceptions
- You can raise an error intentionally using the
raisestatement.
Syntax:
raise ExceptionType("error message")
Example:
raise ValueError("Invalid input")
This helps you stop execution and show meaningful error messages when something goes wrong.
3. Useful Functions in shutil Module
The shutil module allows advanced file operations:
| Function | Purpose |
|---|---|
shutil.copy() | Copies a file |
shutil.copytree() | Copies an entire folder |
shutil.move() | Moves or renames a file/folder |
shutil.rmtree() | Deletes a folder and its contents |
shutil.disk_usage() | Returns total, used, and free disk space |
Example – Checking disk usage:
import shutil
total, used, free = shutil.disk_usage('/')
print(f"Total: {total}, Used: {used}, Free: {free}")
These tools combined let you write robust scripts that can handle errors and manage files effectively.
