Bird
0
0

You want to safely read an environment variable PORT as an integer with a default of 8080 if not set or invalid. Which code snippet correctly does this?

hard📝 Application Q15 of 15
Python - Standard Library Usage
You want to safely read an environment variable PORT as an integer with a default of 8080 if not set or invalid. Which code snippet correctly does this?
Aport = int(os.getenv('PORT') or 8080)
Bport = os.getenv('PORT', 8080)
Ctry:\n port = int(os.getenv('PORT'))\nexcept (TypeError, ValueError):\n port = 8080
Dport = int(os.getenv('PORT', 8080))
Step-by-Step Solution
Solution:
  1. Step 1: Understand the problem requirements

    We must convert PORT to int, use 8080 if missing or invalid (non-integer).
  2. Step 2: Analyze each option

    port = int(os.getenv('PORT', 8080)) fails if PORT is set but not an integer string (raises ValueError). port = os.getenv('PORT', 8080) does not convert to int. port = int(os.getenv('PORT') or 8080) uses or but fails if PORT is set to invalid string (ValueError). try:\n port = int(os.getenv('PORT'))\nexcept (TypeError, ValueError):\n port = 8080 uses try-except to handle missing or invalid values safely.
  3. Final Answer:

    try:\n port = int(os.getenv('PORT'))\nexcept (TypeError, ValueError):\n port = 8080 -> Option C
  4. Quick Check:

    Use try-except to safely convert env var [OK]
Quick Trick: Use try-except to handle invalid env var conversions [OK]
Common Mistakes:
  • Not handling invalid integer strings
  • Assuming default works if env var is invalid
  • Not converting string to int

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes