Combining Python's Logical Operators
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.
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.
Become a Member to join the conversation.