0

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)

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Is the _structure_ of the comparisons always the same? i.e. do you always have one or more `if` conditions, and one or more `or` conditions, and one or more `and` conditions, and one or more `not` conditions? Or can the structure change also? – John Gordon Jan 15 '22 at 21:42
  • 1
    Use `any` and `all`. E.g., `any(x in cell.value for x in ['Bananas', 'Apple'])`. – chepner Jan 15 '22 at 21:45
  • 1
    `in` does not distribute over boolean operations, so you can't reduce a bunch of membership tests to a single membership test. – chepner Jan 15 '22 at 21:53
  • @JohnGordon There is only one if conditions, but multiple and/or/not conditions, e.g. "if ('Bananas' in cell.value or 'Apples' in cell.value and 'large' in cell.value not 'unripe' in cell.value):" – Python_Newbie Jan 16 '22 at 10:01
  • @chepner How can I add "AND" or "NOT" conditions to this? E.g. `if any(x in cell.value for x in ['apples', 'bananas']) not (any x in cell.value for x in ['unripe']):` (but this doesn't work, invalid syntax) – Python_Newbie Jan 16 '22 at 10:18
  • You may still need `and` and `or` to combine calls to `any` and `all`, using `not` as needed to negate things. – chepner Jan 16 '22 at 13:57

1 Answers1

0
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):
John Gordon
  • 29,573
  • 7
  • 33
  • 58