Bird
0
0

What error will occur when running this code if the environment variable SECRET_KEY is not set?

medium📝 Debug Q6 of 15
Python - Standard Library Usage
What error will occur when running this code if the environment variable SECRET_KEY is not set?
import os
print(os.environ['SECRET_KEY'])
AKeyError because 'SECRET_KEY' is missing
BReturns None without error
CPrints an empty string
DTypeError due to missing environment variable
Step-by-Step Solution
Solution:
  1. Step 1: Understand os.environ behavior

    Accessing a missing key in os.environ like a dictionary raises KeyError.
  2. Step 2: Difference from os.getenv

    os.getenv returns None or default if key missing; os.environ['KEY'] raises error.
  3. Final Answer:

    KeyError because 'SECRET_KEY' is missing -> Option A
  4. Quick Check:

    os.environ['missing_key'] raises KeyError [OK]
Quick Trick: os.environ['key'] fails if key missing [OK]
Common Mistakes:
  • Assuming os.environ.get and os.environ[] behave the same
  • Expecting None instead of error
  • Confusing KeyError with TypeError

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes