Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Combining Python's Logical Operators

00:00 Oftentimes the and operator is combined with other Boolean operators, or and not, to create more complex expressions.

00:09 And it’s important to know exactly how Python will evaluate these expressions.

00:15 For example, how would an expression like 5 or 3 and 2 > 1 be evaluated? There’s an or, 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.

00:39 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.

01:05 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 and operations.

01:19 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.

02:10 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.

02:23 So, for example, the > in 2 > 1 will be evaluated before anything involving and or or.

02:34 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.