I like Pointy's Show
so if you wanted to see if
I'm using it for detecting a long-press on mobile: Python has three Boolean operators, or logical operators: 0, 1, and 2. You can use them to check if certain conditions are met before deciding the execution path your programs will follow. In this tutorial, you’ll learn about the 0 operator and how to use it in your code.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 0 operator to approach different problems in a Pythonic way. Even if you don’t use all the features of 0, learning about them will allow you to write better and more accurate code.Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code. 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 0, 1, and 2.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 3 is a subclass of and can take the values 5 or 6:>>>
As you can see in this code, Python implements 3 as a subclass of 4 with two possible values, 5 and 6. These values are in Python. They’re internally implemented as integer numbers with the value 1 for 5 and 3 for 6. Note that both 5 and 6 must be capitalized.Along with the 3 type, Python provides three Boolean operators, or logical operators, that allow you to combine Boolean expressions and objects into more elaborate expressions. Those operators are the following:OperatorLogical OperationConjunction 1Disjunction 2NegationWith 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 0 operator. This operator implements the logical 0 operation. You’ll learn how it works and how to use it either in a Boolean or non-Boolean context.Remove adsGetting Started With Python’s >>> 5 > 3 and 5 == 3 + 2 True >>> 5 < 3 and 5 == 5 False >>> 5 == 5 and 5 != 5 False >>> 5 < 3 and 5 != 5 False 0 OperatorPython’s 0 operator takes two operands, which can be Boolean expressions, objects, or a combination. With those operands, the 0 operator builds more elaborate expressions. The operands in an 0 expression are commonly known as conditions. If both conditions are true, then the 0 expression returns a true result. Otherwise, it returns a false result:>>>
These examples show that an 0 expression only returns 5 when both operands in the expressions are true. Since the 0 operator takes two operands to build an expression, it’s a binary operator.The quick examples above show what’s known as the 0 operator’s truth table: 2 3 4TrueTrueTrueTrueFalseFalseFalseFalseFalseFalseTrueFalseThis table summarizes the resulting truth value of a Boolean expression like 4. The result of the expression depends on the truth values of its operands. It’ll be true if both are true. Otherwise, it’ll be false. This is the general logic behind the 0 operator. However, this operator can do more than that in Python.In the following sections, you’ll learn how to use 0 for building your own expressions with different types of operands.Using Python’s >>> 5 > 3 and 5 == 3 + 2 True >>> 5 < 3 and 5 == 5 False >>> 5 == 5 and 5 != 5 False >>> 5 < 3 and 5 != 5 False 0 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 5 or 6.Comparisons and equality tests are common examples of this type of expression: >>>
All these expressions return 5 or 6, which means they’re Boolean expressions. You can combine them using the 0 keyword to create compound expressions that test two—or more–subexpressions at a time:>>>
Here, when you combine two 5 expressions, you get 5 as a result. Any other combination returns 6. From these examples, you can conclude that the syntax for creating compound Boolean expressions with the 0 operator is the following:
If both subexpressions 8 and 9 evaluate to 5, then the compound expression is 5. If at least one subexpression evaluates to 6, then the result is 6.There’s no limit to the number of 0 operators you can use when you’re building a compound expression. This means that you can combine more than two subexpressions in a single expression using several 0 operators:>>>
Again, if all the subexpressions evaluate to 5, then you get 5. Otherwise, you get 6. Especially as expressions get longer, you should keep in mind that Python evaluates the expressions sequentially from left to right.Remove adsShort-Circuiting the EvaluationPython’s logical operators, such as 0 and 1, use something called short-circuit evaluation, or lazy evaluation. In other words, Python evaluates the operand on the right only when it needs to.To determine the final result of an 0 expression, Python starts by evaluating the left operand. If it’s false, then the whole expression is false. In this situation, there’s no need to evaluate the operand on the right. Python already knows the final result.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 0 operator evaluates the operand on the right only if the first operand is true. In this case, the final result depends on the right operand’s truth value. If it’s true, then the whole expression is true. Otherwise, the expression is false.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 0 expression is false, then the right operand won’t be evaluated.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 0 expressions:
Sometimes you may want to avoid lazy evaluation in a specific Boolean expression. You can do so by using the bitwise operators ( 21, 22, 23). These operators also work in Boolean expressions, but they evaluate the operands eagerly:>>>
In the first expression, the 0 operator works lazily, as expected. It evaluates the first function, and since the result is false, it doesn’t evaluate the second function. In the second expression, however, the bitwise AND operator ( 21) calls both functions eagerly even though the first function returns 6. Note that in both cases, the final result is 6.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 >>> 5 > 3 and 5 == 3 + 2 True >>> 5 < 3 and 5 == 5 False >>> 5 == 5 and 5 != 5 False >>> 5 < 3 and 5 != 5 False 0 Operator With Common ObjectsYou can use the 0 operator to combine two Python objects in a single expression. In that situation, Python internally uses to determine the truth value of the operands. As a result, you get a specific object rather than a Boolean value. You only get 5 or 6 if a given operand explicitly evaluates to 5 or 6:>>>
In these examples, the 0 expression returns the operand on the left if it evaluates to 6. Otherwise, it returns the operand on the right. To produce these results, the 0 operator uses Python’s internal rules to determine an object’s truth value. The Python documentation states these rules like this:
With these rules in mind, look again at the code above. In the first example, the integer number 54 is true (nonzero), so 0 returns the right operand, 56. In the second example, 57 is true, so 0 returns the right operand even though it evaluates to 6.The next example uses an empty list ( 50) as the left operand. Since empty lists evaluate to false, the 0 expression returns the empty list. The only case where you get 5 or 6 is the one where you use a Boolean object explicitly in the expression.Note: If you need to get 5 or 6 from an 0 expression involving common objects rather than Boolean expressions, then you can use 30. This built-in function explicitly returns 5 or 6 depending on the truth value of the specific object you provide as an argument.Here’s how you can summarize the behavior of the 0 operator when you use it with common Python objects instead of Boolean expressions. Note that Python uses the truth value of each object to determine the final result: 71 72 73FalseFalse 71FalseTrue 71TrueTrue 72TrueFalse 72In general, if the operands in an 0 expression are objects instead of Boolean expressions, then the operator returns the object on the left if it evaluates to 6. Otherwise, it returns the object on the right, even when it evaluates to 6.Remove adsMixing Boolean Expressions and ObjectsYou can also combine Boolean expressions and common Python objects within an 0 expression. In that situation, the 0 expression still returns the left operand if it’s false, or else it returns the right operand. The returned value could be 5, 6, or a regular object, depending on which part of the expression provides that result:>>>
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, 5 or 6. The result will depend on which part of the expression provides the final result.Here’s a table that summarizes the behavior of the 0 operator when you combine Boolean expressions and common Python objects: 88 89 90 5True 89 5False 89 6False 6 6True 6To find out what’s returned, Python evaluates the Boolean expression on the left to get its Boolean value ( 5 or 6). Then Python uses its internal rules to determine the truth value of the object on the right.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 01. Try to predict what will be returned in each row.Combining Python Logical OperatorsAs you’ve seen earlier in this tutorial, Python provides two additional logical operators: the 1 operator and the 2 operator. You can use them along with the 0 operator to create more complex compound expressions. If you want to make accurate and clear expressions with multiple logical operators, then you need to consider the of each operator. In other words, you need to consider the order in which Python executes them.Python’s logical operators have low precedence when compared with other operators. However, sometimes it’s healthy to use a pair of parentheses ( 49) to ensure a consistent and readable result:>>> 0These examples combine the 1 operator and the 0 operator in a compound expression. Just like the 0 operator, the 1 operator uses short-circuit evaluation. Unlike 0, however, the 1 operator stops once it finds a true operand. You can see this in the first example. Since 57 is true, the 1 subexpression immediately returns 57 without evaluating the rest of the expression.In contrast, if you enclose the 1 subexpression in a pair of parentheses, then it works as a single true operand, and 16 gets evaluated as well. The final result is 5.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 >>> 5 > 3 and 5 == 3 + 2 True >>> 5 < 3 and 5 == 5 False >>> 5 == 5 and 5 != 5 False >>> 5 < 3 and 5 != 5 False 0 Operator in Boolean ContextsLike all of Python’s Boolean operators, the 0 operator is especially useful in Boolean contexts. Boolean contexts are where you’ll find most of the real-world use cases of Boolean operators.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 0 operator to construct compound Boolean expressions in both 20 statements and 21 loops.Remove ads>>> 5 == 3 + 2 True >>> 5 > 3 True >>> 5 < 3 False >>> 5 != 3 True >>> [5, 3] == [5, 3] True >>> "hi" == "hello" False 20 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 and continues with a condition. A conditional statement can additionally include 27 and 28 clauses.Python conditional statements follow the logic of conditionals in English grammar. If the condition is true, then the 20 code block executes. Otherwise, the execution jumps to a different code block:>>> 1Since 30 holds a negative number, the condition 31 is true. The 20 code block runs, and you get the message 33 printed on your screen. If you change the value of 30 to a positive number, however, then the 27 block runs and Python prints 36. Finally, if you set 30 to zero, then the 28 code block executes. Go ahead and play with 30 to see what happens!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: 2Here, you get the user’s age using and then convert it to an integer number with . The 20 clause checks if 43 is greater than or equal to 3. In the same clause, it checks if 43 is less than or equal to 46. To do this, you build an 0 compound Boolean expression.The three 27 clauses check other intervals to determine the life stage associated with the user’s age.If you run this script from your command line, then you get something like this: 3Depending 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 49 printed to your screen.>>> 5 == 3 + 2 True >>> 5 > 3 True >>> 5 < 3 False >>> 5 != 3 True >>> [5, 3] == [5, 3] True >>> "hi" == "hello" False 21 LoopsThe 21 loop is the second construct that can use 0 expressions to control a program’s execution flow. By using the 0 operator in the 21 statement header, you can test several conditions and repeat the loop’s code block for as long as all conditions are met.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 21 loop with an 0 expression. Here’s a script that simulates a possible solution: 4Inside 57, you create an infinite 21 loop on line 8. If the system is stable and the pressure is below 500 psi, the conditional statement breaks out of the loop and the program finishes.On line 12, the first nested 21 loop runs the standard safety actions while the system pressure stays between 500 psi and 700 psi. In each iteration, the loop gets a new pressure measurement to test the condition again in the next iteration. If the pressure grows beyond 700 psi, then the second loop on line 16 runs the critical safety actions.Note: The implementation of 57 in the example above is intended to show how the 0 operator can work in the context of a 21 loop.However, this isn’t the most efficient implementation you can write. You can refactor 57 to use a single loop without using 0: 5In this alternative implementation, instead of using 0, you use the chained expression 66, which does the same as 67 but is cleaner and more Pythonic. Another advantage is that you call 68 only once, which ends up being more efficient.To run this script, open up your command line and enter the following command: 6The 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. Remove adsUsing Python’s >>> 5 > 3 and 5 == 3 + 2 True >>> 5 < 3 and 5 == 5 False >>> 5 == 5 and 5 != 5 False >>> 5 < 3 and 5 != 5 False 0 Operator in Non-Boolean ContextsThe fact that 0 can return objects besides just 5 and 6 is an interesting feature. For example, this feature allows you to use the 0 operator for conditional execution. Say you need to update a 74 variable if the first item in a given list is equal to a certain expected value. For this situation, you can use a conditional statement:>>> 7Here, 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 75 string. If both checks pass, then 74 changes to 5. You can simplify this code by taking advantage of the 0 operator:>>> 8In 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 0 operator out of the 20 statement you used in the previous example, which means that you’re not working in a Boolean context any longer.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 0 operator works internally.Putting Python’s >>> 5 > 3 and 5 == 3 + 2 True >>> 5 < 3 and 5 == 5 False >>> 5 == 5 and 5 != 5 False >>> 5 < 3 and 5 != 5 False 0 Operator Into ActionSo far, you’ve learned how to use Python’s 0 operator for creating compound Boolean expressions and non-Boolean expressions. You’ve also learned how to use this logical operator in Boolean contexts like 20 statements and 21 loops.In this section, you’ll build a few practical examples that’ll help you decide when to use the 0 operator. With these examples, you’ll learn how to take advantage of 0 for writing better and more Pythonic code.Flattening Nested >>> 5 == 3 + 2 True >>> 5 > 3 True >>> 5 < 3 False >>> 5 != 3 True >>> [5, 3] == [5, 3] True >>> "hi" == "hello" False 20 StatementsOne principle from the states that “Flat is better than nested.” For example, while code that has two levels of nested 20 statements is normal and totally okay, your code really starts to look messy and complicated when you have more than two levels of nesting.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: >>> 9Cool! These two nested 20 statements solve your problem. You first check if the number is positive and then check if it’s lower than 91. In this small example, the call to 92 is a placeholder for your specific calculation, which runs only if both conditions are true.Even though the code works, it’d be nice to make it more Pythonic by removing the nested 20. How can you do that? Well, you can use the 0 operator to combine both conditions in a single compound condition:>>> 0Logical operators like the 0 operator often provide an effective way to improve your code by removing nested conditional statements. Take advantage of them whenever possible.In this specific example, you use 0 to create a compound expression that checks if a number is in a given range or interval. Python provides an even better way to perform this check by chaining expressions. For example, you can write the condition above as 97. That’s a topic for the following section.Checking Numeric RangesWith a close look at the example in the section below, you can conclude that Python’s 0 operator is a convenient tool for checking if a specific numeric value is inside a given interval or range. For example, the following expressions check if a number 99 is between 3 and 91, both inclusive:>>> 1In the first expression, the 0 operator first checks if 99 is greater than or equal to 3. Since the condition is true, the 0 operator checks if 99 is lower than or equal to 91. The final result is true because the second condition is also true. This means that the number is within the desired interval.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: >>> 2In this example, 08 takes 09 as an argument. It also takes 10 and 11, which define the target interval. Note that these arguments have , which means they’re optional arguments.Your 08 function returns the result of evaluating an 0 expression that checks if 09 is between 10 and 11, both inclusive.Note: Unintentionally writing 0 expressions that always return 6 is a common mistake. Suppose you want to write an expression that excludes values between 3 and 91 from a given computation.To achieve this result, you start with two Boolean expressions:
With these two expressions as a starting point, you think of using 0 to combine them in a single compound expression. However, no number is lower than 3 and greater than 91 at the same time, so you end up with an always-false condition:>>> 3In this case, 0 is the wrong logical operator to approach the problem at hand. You should use the 1 operator instead. Go ahead and give it a try!Even though using the 0 operator allows you to check gracefully if a number is within a given interval, there’s a more Pythonic technique to approach the same problem. In mathematics, you can write 0 < x < 10 to denote that x is between 0 and 10.In most programming languages, this expression doesn’t make sense. In Python, however, the expression works like a charm: >>> 4In a different programming language, this expression would start by evaluating 29, which is true. The next step would be to compare the true Boolean with 91, which doesn’t make much sense, so the expression fails. In Python, something different happens.Python internally rewrites this type of expression to an equivalent 0 expression, such as 32. It then performs the actual evaluation. That’s why you get the correct result in the example above.Just like you can chain several subexpressions with multiple 0 operators, you can also chain them without explicitly using any 0 operators:>>> 5You can also use this Python trick to check if several values are equal: >>> 6Chained 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. Remove adsChaining Function Calls ConditionallyIf you’ve ever worked with Bash on a Unix system, then you probably know about the 35 construct. This is a handy technique that allows you to run several commands in a chain. Each command runs if and only if the previous command was successful: 7These examples use Bash’s short-circuit AND operator ( 36) to make the execution of the 37 command dependent on the success of the 38 command.Since Python’s 0 also implements the idea of lazy evaluation, you can use it to emulate this Bash trick. For example, you can chain a series of function calls in a single 0 expression like the following: 8In this case, Python calls 41. If the function’s return value evaluates to a true value, then Python calls 42, and so on. If one of the functions returns a false value, then Python won’t call the rest of the functions.Here’s an example that uses some 43 functions to manipulate a text file:>>> 9Nice! In a single line of code, you run three functions conditionally without the need for an 20 statement. In this specific example, the only visible difference is that returns the number of bytes it wrote to the file. The interactive shell automatically displays that value to the screen. Keep in mind that this difference isn’t visible when you run the code as a script.ConclusionPython’s 0 operator allows you to construct compound Boolean expressions that you can use to decide the course of action of your programs. You can use the 0 operator to solve several problems both in Boolean or non-Boolean contexts. Learning about how to use the 0 operator properly can help you write more Pythonic code.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 0 operator to make decisions in your Python code.Mark as Completed 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 🐍 Python Tricks 💌 Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team. Send Me Python Tricks » About Leodanis Pozo Ramos Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites. » More about LeodanisEach tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are: Aldren Bartosz Sadie Master Real-World Python Skills With Unlimited Access to Real Python Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Level Up Your Python Skills » Master Real-World Python Skills Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Level Up Your Python Skills » What Do You Think? Rate this article: Tweet Share Share EmailWhat’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know. Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. and get answers to common questions in our support portal. When determining if a number is outside a range it's best to use this operator?When determining whether a number is outside a range, it's best to use this logical operator. This operator connects two Boolean expressions into one. One, and only one, of the expressions must be true for the overall expression to be true.
When determining whether a number is inside a range which logical operator is it best to use?Q: When determining whether a number is inside a range, which logical operator is it best to use? A: Logical "and" Operator: Logical operator combines the results of one or more conditions.
Which of the following logical operators should be used to reverse the value of an expression?The functions AND and OR may be used to test two or more logical expressions, while the NOT function is used to reverse the truth value of a logical expression. The XOR function returns TRUE when one, and only one, of the logical expressions is true.
Which operator determines whether two expressions are both true?Using the OR operator, we can create a compound expression that is true when either of two conditions are true. Imagine a program that determines whether a student is eligible to enroll in AP CS A.
|