How can I access the value of an environment variable in Python?

Using os.environ: The os.environ dictionary provides access to environment variables, which I’ve relied on extensively in my projects. It’s straightforward and lets you provide a fallback value if needed.

import os
value = os.environ.get('MY_ENV_VAR', 'default_value')  # 'default_value' if the variable is not set
print(value)

This exact match keyword: ‘os.environ’ is handy because it ensures you don’t hit runtime errors when a variable isn’t set.