Python IF multiple "and" "or" in one statement
41,214
Use parenthesis to group the conditions:
if value[6] in target and (value[0] in target or value[1] in target):
Note that you can make the in
lookups in constant time if you would define the target
as a set:
target = {1,2,3,4,5,6,f}
And, as mentioned by @Pramod in comments, in this case value[6]
would result in an IndexError
since there are only 6 elements defined in value
and indexing is 0-based.
Author by
yingnan liu
Updated on July 23, 2022Comments
-
yingnan liu almost 2 years
I am just wondering if this following if statement works:
value=[1,2,3,4,5,f] target = [1,2,3,4,5,6,f] if value[0] in target OR value[1] in target AND value[6] in target: print ("good")
My goal is to make sure the following 2 requirements are all met at the same time: 1. value[6] must be in target 2. either value[0] or value[1] in target Apologize if I made a bad example but my question is that if I could make three AND & OR in one statement? Many thanks!