Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python IF multiple "and" "or" in one statement

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!

like image 794
yingnan liu Avatar asked Mar 30 '16 01:03

yingnan liu


People also ask

How do you do multiple or if statements in Python?

Here we'll study how can we check multiple conditions in a single if statement. This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.

Can you have 3 conditions in an if statement in Python?

Test multiple conditions with a single Python if statementTo test multiple conditions in an if or elif clause we use so-called logical operators. These operators combine several true/false values into a final True or False outcome (Sweigart, 2015).

What is && and || in Python?

Some of the operators you may know from other languages have a different name in Python. The logical operators && and || are actually called and and or . Likewise the logical negation operator ! is called not . So you could just write: if len(a) % 2 == 0 and len(b) % 2 == 0: or even: if not (len(a) % 2 or len(b) % 2):

Can you include multiple conditions in an if statement Python?

If we want to join two or more conditions in the same if statement, we need a logical operator. There are three possible logical operators in Python: and – Returns True if both statements are true. or – Returns True if at least one of the statements is true.


1 Answers

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.

like image 131
alecxe Avatar answered Oct 19 '22 03:10

alecxe