Combining Python's Logical Operators
and operator is combined with other Boolean operators,
not, to create more complex expressions.
00:09 And it’s important to know exactly how Python will evaluate these expressions.
For example, how would an expression like
5 or 3 and 2 > 1 be evaluated? There’s an
and, and also a
>. How does Python know which operation to perform first? Python uses something called operator precedence to determine which operations to perform in which order in a complex expression.
This is basically the same thing as order of operations you learned in math class, but since Python has so many operations, you can imagine there are many more rules. For Boolean operations, all
and operations are performed first, from left to right, then the
or operations are performed. So in this case, the
3 and 2 > 1 will be evaluated first.
Then the result of that will be connected with
or to the expression
5. This expression doesn’t have a
not but if it did, the
not would be evaluated even before any
However, just like in math class, you can use parentheses if you want a lower-ordered operation to be evaluated first. So if you want the
5 or 3 to be performed first, you would put parentheses around them.
01:35 FYI, in Python you always use parentheses, often nested inside other sets of parentheses, to group operations like this. In math class, you often used other symbols, like brackets and braces, if you had one set inside another.
01:51 But those symbols have other meanings in Python, so for grouping operations, it’s always parentheses. In some cases, you might want to add parentheses that aren’t strictly necessary just to make clear to yourself and anyone else who might read your code which operation is being performed first.
So you could put parentheses around the
and operation just to make things easier to read. Finally, as a group, Boolean operators have a much lower precedence than other operations.
So, for example, the
2 > 1 will be evaluated before anything involving
Now that you know how to put together expressions involving
and, let’s take a look at when you might use them.
Become a Member to join the conversation.