**Why do it?** To prevent your program from crashing when it tries to access a variable, file, or dictionary key that isn't there. This is crucial when dealing with user input, API responses, or optional configuration settings.
**How to do it:**
- **For Variables (None check):** In Python, "empty" or "missing" is often represented by `None`.
```python
user_input = None
if user_input is not None:
print(f"Processing: {user_input}")
else:
print("No input provided.")
```
**For Dictionaries (Key check):** Before accessing a key, check if it exists or use `.get()` to provide a default.
```python
config = {'theme': 'dark'}
# Method A: The 'in' operator
if 'volume' in config:
print(config['volume'])
# Method B: .get() (Safer and more Pythonic)
# Returns 50 if 'volume' doesn't exist; doesn't crash.
volume = config.get('volume', 50)
```
For Files:
```python
import os
if os.path.exists("data.csv"):
# Safe to open
pass
```