0

I am having trouble with some if statements in my script. I run from a terminal using ./iojson.py "nodev", but the code still executes the if statements for "enum" or "snum", which cause my script to stop due to a NameError.

The code is below:

devicelist = sys.argv[1]
if devicelist == "snum" or "enum":
    if devicelist == "snum":
        print("It executed snum")
        with open('SNUM.txt') as f:
            content = f.readlines()
    if devicelist == "enum":
        print("It executed enum")
        with open('ENUM.txt') as f:
            content = f.readlines()
    content = [x.strip() for x in content]
    devices = ''.join(content)
    data['attachments'].append({
        'fields' : [{
            'title' : 'Serial numbers:',
            'value' : devices
            }]
        })
elif devicelist == "nodev":
    print("It executed nodev")
    pass

After execution, the response is:

Traceback (most recent call last):
  File "./iojson.py", line 43, in <module>
    content = [x.strip() for x in content]
NameError: name 'content' is not defined

My understanding though is that it should never have gotten to the content variable in the first place. What am I doing wrong?

jagdpanzer
  • 693
  • 2
  • 10
  • 35
  • 3
    Well firstly this is not doing what you think: `if devicelist == "snum" or "enum":`, it's going to evaluate to true on the second `or` condition as it's viewed as `or 'enum'` which converts the string to `True`, you want `if devicelist == "snum" or devicelist == "enum":` secondly where is context defined here? – EdChum Apr 18 '17 at 14:09
  • @EdChum youre right for the `if` but you have read context instead of `content` and its value is `content = f.readlines()` – WhatsThePoint Apr 18 '17 at 14:11
  • 3
    Possible duplicate of [How do I test one variable against multiple values?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – Lafexlos Apr 18 '17 at 14:12

1 Answers1

3
if devicelist == "snum" or "enum":

will always be true.

This is what the compiler will check:

if (devicelist == "snum") or "enum":

The first check is False, while the second check for casting "enum" to a boolean is always True.

Workaround:

if devicelist in ("snum", "enum"):
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50