Python_Newbie
Python_Newbie

Reputation: 1

How to best write a long list of "or" "and" "not" operators?

I am using Python/Openpyxl to search through strings in an Excel spreadsheet and sum up the numerical values. How do I write/format my script to have multiple OR, NOT, AND operators? (Sorry I appreciate this is probably a very basic question, but I am very new to coding!).

My script (excerpt) is currently this:

if 'Bananas' in cell.value or 'Apples' in cell.value:

However, I would like to write something longer, and ideally in a 'neat', extendable format, such as:

if:
 - 'Bananas'

or:
 - 'Apples'
 - 'Oranges'

and:
 - 'Large'

not:
 - 'Unripe'

...in cell.value:

Can someone tell me how I can format/write this in proper Python script? (Ideally in a format I can extend to, say, 20+ [or, and, not] conditions)

Upvotes: 0

Views: 92

Answers (1)

John Gordon
John Gordon

Reputation: 33343

if_values = ['Bananas', 'Apples', 'Oranges']
and_values = ['Large']
not_values = ['Unripe']

if any(item in cell.value for item in if_values) \
    and any(item in cell.value for item in and_values) \
    and not any(item in cell.value for item in not_values):

Upvotes: 0

Related Questions