Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using the Python and Operator Show
Python has three Boolean operators, or logical operators: In this tutorial, you’ll learn how to:
You’ll also code a few practical examples that will help you understand how to use the Working With Boolean Logic in PythonBack in 1854, George Boole authored
The Laws of Thought, which contains what’s known as Boolean algebra. This algebra relies on two values: true and false. It also defines a set of Boolean operations, also known as logical operations, denoted by the generic operators
These Boolean values and operators are pretty helpful in programming. For example, you can construct arbitrarily complex Boolean expressions with the operators and determine their resulting truth value as true or false. You can use the truth value of Boolean expressions to decide the course of action of your programs. In Python, the Boolean type >>>
As you can see in this code, Python implements Along with the
With these operators, you can connect several Boolean expressions and objects to build your own expressions. Unlike other languages, Python uses English words to denote Boolean operators. These words are keywords of the language, so you can’t use them as identifiers. In this tutorial, you’ll learn about Python’s Getting Started With Python’s and OperatorPython’s >>>
These examples show that an The quick examples above show what’s known as the
This table summarizes the resulting truth value of a Boolean expression like In the following sections, you’ll learn how to use Using Python’s and Operator With Boolean ExpressionsYou’ll typically use logical operators to build compound Boolean expressions, which are combinations of
variables and values that produce a Boolean value as a result. In other words, Boolean expressions return Comparisons and equality tests are common examples of this type of expression: >>>
All these expressions return >>>
Here, when you combine two
If both
subexpressions There’s no limit to the number of >>>
Again, if all the subexpressions evaluate to Short-Circuiting the EvaluationPython’s logical
operators, such as To determine the final result of an Having a false left operand automatically makes the whole expression false. It would be a waste of CPU time to evaluate the remaining operand. Python prevents this by short-circuiting the evaluation. In contrast, the To demonstrate the short-circuiting feature, take a look at the following examples: >>>
Here’s how this code works:
Python processes Boolean expressions from left to right. It stops when it no longer needs to evaluate any further operands or subexpressions to determine the final outcome. To sum up this concept, you should remember that if the left operand in an Short-circuit evaluation can have a significant impact on your code’s performance. To take advantage of that, consider the following tips when
you’re building
Sometimes you may want to avoid lazy evaluation in a specific
Boolean expression. You can do so by using the bitwise operators ( >>>
In the first expression, the Even though this trick works, it’s generally discouraged. You should use bitwise operators to manipulate bits, and Boolean operators to work with Boolean values and expressions. For a deeper dive into bitwise operators, check out Bitwise Operators in Python. Using Python’s and Operator With Common ObjectsYou can use the >>>
In these
examples, the
With these rules in mind, look again at the code above. In the first example, the integer number The next example uses an empty list ( Here’s how you can summarize the behavior of the
In general, if the operands in an Mixing Boolean Expressions and ObjectsYou can also combine Boolean expressions and common Python objects within an >>>
These examples use a combination of Boolean expressions and common objects. In each pair of examples, you see that you can get either a non-Boolean object or a Boolean value, Here’s a table that summarizes the behavior of the
To find out what’s returned, Python evaluates the Boolean expression on the left to get its Boolean value ( As an exercise to test your understanding, you could try to rewrite this table by swapping the order of the operands in the third column to Combining Python Logical OperatorsAs you’ve seen earlier in this tutorial, Python provides two additional logical operators: the Python’s logical operators have low precedence when compared with other operators. However, sometimes it’s healthy to use a pair of parentheses (
>>>
These examples combine the In contrast, if you enclose the The takeaway is that if you’re using multiple logical operators in a single expression, then you should consider using parentheses to make your intentions clear. This trick will also help you get the correct logical result. Using Python’s and Operator in Boolean ContextsLike all of Python’s Boolean operators, the Two main structures define Boolean contexts in Python:
These two structures are part of what you’d call control flow statements. They help you decide your programs’ execution path. You can use Python’s if StatementsBoolean expressions are commonly known as conditions because they typically imply the need for meeting a given requirement. They’re pretty useful in the context of conditional statements. In Python, this type of statement starts with the Python conditional statements follow the logic of conditionals in English grammar. If the condition is true, then the >>>
Since Now say you want to make sure that two conditions are met—meaning that they’re both true—before running a certain piece of code. To try this out, suppose you need to get the age of a user running your script, process that information, and display to the user their current life stage. Fire up your favorite code editor or IDE and create the following script:
Here, you get the user’s age using
The three If you run this script from your command line, then you get something like this:
Depending on the age you enter at the command line, the script takes one course of action or another. In this specific example, you provide an
age of 25 years and get the message while LoopsThe Say you’re prototyping a control system for a manufacturer. The system has a critical mechanism that should work with a pressure of 500 psi or lower. If the pressure goes over 500 psi while staying under 700 psi, then the system has to run a given series of standard safety actions. For pressures greater than 700 psi, there are a whole new set of safety actions that the system must run. To approach this problem, you can use a
Inside On line 12, the first nested To run this script, open up your command line and enter the following command:
The output on your screen should be a little different from this sample output, but you can still get an idea of how the application works. Using Python’s and Operator in Non-Boolean ContextsThe fact that >>>
Here, the conditional checks if the list has at least one item. If so, it checks if the first item in the list is equal to the >>>
In this example, the highlighted line does all the work. It checks both conditions and makes the corresponding assignment in one go. This expression takes the The code in the example above is more concise than the
equivalent conditional statement you saw before, but it’s less readable. To properly understand this expression, you’d need to be aware of how the Putting Python’s and Operator Into ActionSo far, you’ve learned how to use Python’s In this section, you’ll build a few practical examples that’ll help you decide when to use the Flattening Nested if StatementsOne principle from the Zen of Python states that “Flat is better than nested.” For example, while code that has two levels of nested Say you need to test if a given number is positive. Then, once you confirm that it’s positive, you need to check if the number is lower than a given positive value. If it is, you can proceed with a specific calculation using the number at hand: >>>
Cool! These two nested Even though the code works, it’d be nice to make it more Pythonic by removing the nested >>>
Logical operators
like the In this specific example, you use Checking Numeric RangesWith a close look at the example in the section below, you can conclude that Python’s >>>
In the first expression, the In the second example, the first condition is true, but the second is false. The general result is false, which means the number isn’t in the target interval. You can enclose this logic in a function and make it reusable: >>>
In this example, Your Even though using the In most programming languages, this expression doesn’t make sense. In Python, however, the expression works like a charm: >>>
In a different programming language, this expression would start by evaluating Python internally rewrites this type of expression to an equivalent Just like you can chain several subexpressions with multiple >>>
You can also use this Python trick to check if several values are equal: >>>
Chained comparison expressions are a nice feature, and you can write them in various ways. However, you should be careful. In some cases, the final expression can be challenging to read and understand, especially for programmers coming from languages in which this feature isn’t available. Chaining Function Calls ConditionallyIf you’ve ever worked with Bash on a
Unix system, then you probably know about the
These examples use Bash’s short-circuit AND operator ( Since Python’s
In this case, Python calls Here’s an example that uses some
>>>
Nice! In a single line of code, you run three functions conditionally without the need for an ConclusionPython’s In this tutorial, you learned how to:
Going through the practical examples in this tutorial can help you get a general idea of how to use the Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using the Python and Operator |