Question

Difficulty: HardBasic Scripting Languages and Constructs

A desktop administrator is troubleshooting a custom administrative Python script (`.py`) designed to monitor workstation resource utilization. The script fetches a threshold limit from a system environment variable using `os.environ.get("MAX_RAM_MB")` and evaluates it against an integer representing available system memory (`free_ram`). During testing, the script crashes with the error: `TypeError: '<' not supported between instances of 'int' and 'str'`. Which of the following is the BEST resolution to correct this script error?

  1. Convert the environment variable value from a string to an integer data type using the int() function prior to comparison.Answer
  2. B
    Enclose both variables in double quotes within the conditional statement to trigger automatic data type coercion.
  3. C
    Append the /i command-line switch to the environment variable retrieval statement to force numerical parsing.
  4. D
    Execute the chmod +x command on the script file to grant numeric evaluation privileges to the script interpreter.

Answer

Convert the environment variable value from a string to an integer data type using the int() function prior to comparison.
System environment variables return values as string data types. In Python, comparing an integer directly against a string using relational operators causes a runtime `TypeError`. Explicitly casting the string output to an integer using `int()` resolves the data type mismatch and permits accurate numeric comparison.

Step-by-Step Solution

1
Identify the data type returned by environment variable constructs.
Operating system environment variables are always retrieved as string values.
Scripting engines read environment variables from system storage as plain text strings.
2
Analyze the error cause in the conditional construct.
The expression compares an integer (`free_ram`) to a string (`MAX_RAM_MB`), causing a runtime `TypeError`.
Strongly typed comparisons do not implicitly convert text representations of numbers into actual integer data types.
3
Apply explicit data type conversion (casting).
`int(os.environ.get("MAX_RAM_MB"))` evaluates to an integer.
Casting the retrieved string to an integer allows numerical relational operators (`<`, `>`, `==`) to function correctly.

Key Concept

Environment Variable Data Types and Type Casting in Scripts
Estimated Time:2m 0s
Rate this question