0
0
Pythonprogramming~20 mins

Environment variables usage in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Environment Variable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this environment variable read?

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?

Python
import os
os.environ['MY_VAR'] = 'hello'
value = os.getenv('MY_VAR')
print(value)
ANone
Bhello
C'' (empty string)
DKeyError
Attempts:
2 left
💡 Hint

Remember that os.getenv returns the value of the environment variable if it exists.

Predict Output
intermediate
2:00remaining
What does this code print when variable is missing?

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?

Python
import os
value = os.getenv('NOT_SET', 'default')
print(value)
AKeyError
BNone
C'' (empty string)
Ddefault
Attempts:
2 left
💡 Hint

Check what the second argument to os.getenv does.

Predict Output
advanced
2:00remaining
What error does this code raise?

Look at this code:

import os
value = os.environ['MISSING_VAR']
print(value)

What happens if MISSING_VAR is not set in the environment?

Python
import os
value = os.environ['MISSING_VAR']
print(value)
AKeyError
BNone
C'' (empty string)
DAttributeError
Attempts:
2 left
💡 Hint

Accessing environment variables via os.environ like a dictionary raises an error if the key is missing.

Predict Output
advanced
2:00remaining
What is the output of this environment variable update?

Consider this code:

import os
os.environ['TEST_VAR'] = '123'
os.environ['TEST_VAR'] = '456'
print(os.getenv('TEST_VAR'))

What will be printed?

Python
import os
os.environ['TEST_VAR'] = '123'
os.environ['TEST_VAR'] = '456'
print(os.getenv('TEST_VAR'))
A456
BNone
C123
DKeyError
Attempts:
2 left
💡 Hint

Think about what happens when you assign a new value to the same environment variable key.

🧠 Conceptual
expert
2:00remaining
Which option correctly explains environment variable visibility?

Which statement about environment variables in Python is true?

AEnvironment variables are shared across all running Python processes automatically.
BChanges to <code>os.environ</code> in a Python script affect the parent process environment.
CEnvironment variables set in a Python script are visible to child processes spawned after the change.
DEnvironment variables can be set permanently for all future Python scripts by modifying <code>os.environ</code>.
Attempts:
2 left
💡 Hint

Think about how environment variables propagate between processes.