Does the order of logical operators matter?

Question

If we are combining multiple logical statements, and we kept the statement order fixed, does the order of the logical operators (or/and) matter?

Answer

Yes and no. It depends on how many logical statements there are.

When there is only one logical statement, it’s always going to evaluate the same way, because it’s just a single statement.
num < 3
num > 6

When there are two logical statements, order does not matter, because we can only apply one logical statement & (and) or | (or) between them.
(num < 3) | (num > 6)
is the same as
(num > 6) | (num < 3)

When we have more than two statements, that is when order does start to matter.

Say that we have three statements, and wish to combine them using one | and one &. Like so, in different operator orders.

A & B | C
A | B & C

These will not necessarily be the same result. For instance, take these values.

A = False
B = False
C = True

A & B | C
False & False | True = True
A | B & C
False | False & True = False

So, order of the logical operators will matter. This is mainly due to the order of operations, as & (and) is evaluated before any | (or) operators.

6 Likes

I think that the example is not a different order of operators example, there are two different set of operations.
Different order will be if the second statement was:
True | False & false.

or am I mistaken?

1 Like

Why did passing ‘&’ did not return any value in this case as logically it made sense to retrieve data of March ‘and’ April.

3 Likes

You are right, putting & instead of | in the lesson’s exercise does not return any output in the screen. I hadn’t thought making this change and check the result.
In the beginning I could not give an explanation but later I think I realised what is going on.

Sometimes, the logic behind our expessions in our written/spoken language is somewhat different from the logic of the written code.
I mean, if as a Head of a clinic you wanted to retrieve data of both months March, April , you would probably tell your associates “provide me data for March and April”.
However, if you told them “provide me data for March or April”, this would be ambiguous; some might give you data only for March, some only for April and some might give for both months just to be sure that you will not give them extra work later.

However, in the code, the logic is slightly different and hopefully more clear.
Columns March , April are actually two different , distinct conditions. So , in order to select the rows that refer to these 2 columns/months we have to use | (or).
& (and) cannot be applied because one condition (March) excludes the other (April).

& (and) can be used when , selecting rows, each logical statement refers to diffferent columns e.g.
march_west = df[(df.month == ‘March’) & (df.clinic_west == 96)]
print(march_west)

I noticed that this different use of OR AND in written/spoken language comparing to coding ( | , & ) also appears in the particular CodeAcademy lesson.
The author writes in the Instructions: " Create the variable march_april , which contains the data from March and April".
And just in the 2 next lines: " Do this using two logical statements combined using | , which means “or”.

You can see a very good graphical illustration of the OR AND operators in the 2 links below.
Although they refer to SQL , not python , I believe they help capture the difference (obviously from a statistical point of view); at least for me it was very helpful.
Just look only at the graphs and the sentences below them.

https://www.codecademy.com/paths/data-science/tracks/sql-basics/modules/dspath-sql-queries/lessons/queries/exercises/and

https://www.codecademy.com/paths/data-science/tracks/sql-basics/modules/dspath-sql-queries/lessons/queries/exercises/or

10 Likes

Unless I am misinformed, & and | are bitwise operators, not logical operators in Python. They are also intersection and union operators in the sets module. The logical operators are and and or.

if (x < 6) and (y > 6):

if (x < 5) or (x > 10):

Bitwise operators work on binary numbers.

15 & 8  => 8

Why?

1 1 1 1
1 0 0 0

The two numbers have only the 2^3 bit in common, which is the bit representing the number 8.

7 | 8  => 15

Why?

0 1 1 1
1 0 0 0

We see that between the two numbers there is a bit set in each of the four bits, which represents 15.

1 Like

I am having difficulty having proper comprehension of your explanation. This is because i got the following result which clearly contradict your points, I will be glad if you can help with further clarifications.

test_df = pd.DataFrame([
    [1, 'Ola', 80, 25, 'A', 'Passed'],
    [2, 'Bola', 42, 24, 'E', 'Failed'],
    [3, 'Tayo', 99, 22, 'A', 'Passed'],
    [4, 'Adebola', 95, 27, 'A', 'Passed'],
    [5, 'Marvel', 40, 24, 'E', 'Failed']
    ],
    columns= ['id', 'name', 'score', 'age', 'grade', 'status'])
print(test_df)
(.venv) sodiqafolayan@Sodiqs-MacBook-Pro hello % /Users/sodiqafolayan/Desktop/Grand_Project/hello/.venv/bin/python /Users/sodiqafolayan/Desktop/Grand_Project/hello/hello.py
   id     name  score  age grade  status
0   1      Ola     80   25     A  Passed
1   2     Bola     42   24     E  Failed
2   3     Tayo     99   22     A  Passed
3   4  Adebola     95   27     A  Passed
4   5   Marvel     40   24     E  Failed
exa = test_df[(test_df.age > 25) & (test_df.score > 50)]
print(exa)
  id     name  score  age grade  status
3   4  Adebola     95   27     A  Passed
 id     name  score  age grade  status
0   1      Ola     80   25     A  Passed
2   3     Tayo     99   22     A  Passed
3   4  Adebola     95   27     A  Passed

As you can see from the above, both “and” & and “or” | worked logically as the way we express both in daily conversation.

I will appreciate if you can advise on where i am wrong

Hi, I am no expert or anything (please correct me if i’m wrong here) but I think your example is different because you’re evaluating two different columns (age and score).

In the example we’re evaluating only one column (month). The “normal” logic on “or” and “and” doesn’t apply here because “and” (&) would ask the code to provide rows in which the month is BOTH march and april at the same time.

On the other hand if you use “or” you would be asking the code to provide those rows in which month is EITHER march “or” (|) april.

1 Like

This exercise is wrong in saying: " In Python, | means “or” and & means “and”."

Python uses the syntax and , or , and not , whereas in Pandas are &, | and ~ (not),and parentheses (…) is best to always add to!

Those are Bitwise Operators. Nothing wrong here. Pandas is not core Python and plays no part in this.

Sorry, my expression wasn’t clear that I’m pointing to the exact sentence in the linked exercise per se, not your post, and yes it is Bitwise Operators in Python and logical Operators are and , or , and not in Python.

Very good explanation @jminer583

In addition to what @corepro76625 , try changing the age of Marvel to 28. Then use both " | " and " &" for your query.

Using &

Using |

Notice these difference between the operators, I think this means that “&” means AND in Logic, and | means OR in logic.