Teracan
Teracan

Reputation: 105

Python - chaining of or operators in if statement don't provide expected results

Trying to chain OR operators in an if statement to cut down on redundant code but it seems only the first 2 operators are executed.

what I have now which works, but is messy

if out is "" or out != "sql":
    if out !=  "csv":
        print '\t*** ERROR  **'
    else:
        break
else:
    break

Trying to do similar to the following:

if out is "" or out != "sql" or out !=  "csv":
    print '\t*** ERROR  **'     
else:
    break

If the var is equal to blank, or not equal to sql or csv, then print an error, else continue.

Output {sql|csv}: csv
        *** ERROR **

The above should be != csv (False) and continue to the next line, not printing out the error

Upvotes: 1

Views: 1189

Answers (2)

Andrew Allen
Andrew Allen

Reputation: 8002

Another alternative

if a not in ["sql", "csv"]:

Upvotes: 3

jfaccioni
jfaccioni

Reputation: 7509

This

if out is "" or out != "sql":
    if out !=  "csv":

Is equivalent to

if (out is "" or out != "sql") and (out !=  "csv"):

Upvotes: 1

Related Questions