0
0
Pythonprogramming~5 mins

Environment variables usage in Python

Choose your learning style9 modes available
Introduction

Environment variables let your program use settings from outside the code. This helps keep secrets safe and makes your program flexible.

You want to keep passwords or keys secret and not write them in your code.
You need to change settings like database address without changing the program.
You want the same program to work on different computers with different settings.
You want to avoid hardcoding values that might change later.
Syntax
Python
import os

value = os.getenv('VARIABLE_NAME', 'default_value')

os.getenv reads the value of an environment variable.

You can provide a default value if the variable is not set.

Examples
Get the value of API_KEY from environment. Returns None if not set.
Python
import os

api_key = os.getenv('API_KEY')
Get PORT or use '8080' if PORT is not set.
Python
import os

port = os.getenv('PORT', '8080')
Get SECRET from environment. Raises KeyError if not set.
Python
import os

secret = os.environ['SECRET']
Sample Program

This program greets the user by name if the environment variable USER_NAME is set. Otherwise, it says Hello, Guest!

Python
import os

# Try to get USER_NAME from environment
user = os.getenv('USER_NAME', 'Guest')

print(f'Hello, {user}!')
OutputSuccess
Important Notes

Environment variables are strings. Convert them if you need numbers.

Use os.environ to access variables like a dictionary, but it raises an error if the variable is missing.

Set environment variables outside your program, for example in your terminal or system settings.

Summary

Environment variables let your program get settings from outside the code.

Use os.getenv to safely read variables with optional defaults.

Keep secrets and settings flexible by using environment variables.