Consider this Python code that reads an environment variable named MY_VAR:
import os
os.environ['MY_VAR'] = 'hello'
value = os.getenv('MY_VAR')
print(value)What will this code print?
import os os.environ['MY_VAR'] = 'hello' value = os.getenv('MY_VAR') print(value)
Remember that os.getenv returns the value of the environment variable if it exists.
The code sets the environment variable MY_VAR to 'hello'. Then os.getenv('MY_VAR') reads it and returns 'hello'. So the print outputs 'hello'.
Given this code snippet:
import os
value = os.getenv('NOT_SET', 'default')
print(value)What will be printed if the environment variable NOT_SET is not defined?
import os value = os.getenv('NOT_SET', 'default') print(value)
Check what the second argument to os.getenv does.
The second argument to os.getenv is the default value returned if the environment variable is not set. So it prints 'default'.
Look at this code:
import os value = os.environ['MISSING_VAR'] print(value)
What happens if MISSING_VAR is not set in the environment?
import os value = os.environ['MISSING_VAR'] print(value)
Accessing environment variables via os.environ like a dictionary raises an error if the key is missing.
Accessing os.environ['MISSING_VAR'] raises a KeyError if the variable is not set.
Consider this code:
import os
os.environ['TEST_VAR'] = '123'
os.environ['TEST_VAR'] = '456'
print(os.getenv('TEST_VAR'))What will be printed?
import os os.environ['TEST_VAR'] = '123' os.environ['TEST_VAR'] = '456' print(os.getenv('TEST_VAR'))
Think about what happens when you assign a new value to the same environment variable key.
The second assignment overwrites the first. So TEST_VAR becomes '456'. The print outputs '456'.
Which statement about environment variables in Python is true?
Think about how environment variables propagate between processes.
Modifying os.environ affects only the current process and its child processes spawned after the change. It does not affect the parent or other running processes.