mercredi 8 janvier 2020

Python complex compound boolean expression

It is not a problem to write each boolean condition on its own, but sometimes it would be nice to group test variables together and test them on a similar condition. Besides, if the contents of the test expression - in the brackets - were able to be modified dynamically each time the program is run, this would bring even more value.

This is a reproducible example of the code, where the test strings could be as well variables of a type str:

AnimalString = 'We were looking for a mouse in our house.'

# Working, but too long, if-statement
if 'dolphin' in AnimalString or 'mouse' in AnimalString or 'cow' in AnimalString:
    print('At least one listed animal is in the AnimalString.')

# Desired complex compound boolean expression --> not working
if ('dolphin' or 'mouse' or 'cow') in AnimalString:
    print('At least one listed animal is in the AnimalString.')

# Desired complex compound boolean expression --> neither not working
if 'dolphin' or 'mouse' or 'cow' in AnimalString:
    print('At least one listed animal is in the AnimalString.')

I know why the last two paragraphs of the code do not work based on the SO posts - here and here. Code in the second paragraph returns a boolean expression result as True or True or False, which falsely prints the message. Code in the third paragraph tests only for the string 'dolphin' in the AnimalString and gives no output.

Is there a way to shorten a working, but complex, compound boolean condition in a comprehensible manner?

Aucun commentaire:

Enregistrer un commentaire