You can compare objects using normal operators: <, <=, >, >=, and so forth. == is the equality test operator, and either != or <> may be used as the "not equal to" test. There are also in and not in operators to test membership in sequences (lists, tuples, strings, and dictionaries) as well as is and is not operators to test whether two objects are the same.
Expressions that return a Boolean value may be combined into more complex expressions using the and, or, and not operators. This code snippet checks to see if a variable is within a certain range:
Python offers a nice shorthand for this particular type of compound statement; you can write it as you would in a math paper:
Various rules of precedence apply; when in doubt, you can use parentheses to make sure Python interprets an expression the way you want it to. This is probably a good idea for complex expressions, regardless of whether it's necessary, because it makes it clear to future maintainers of the code exactly what's happening. See the appendix for more details on precedence.
The rest of this section provides more advanced information. If this is your first read through this book as you're learning the language, you may want to skip over it.
The and and or operators return objects. The and operator returns either the first false object (that an expression evaluates to) or the last object. Similarly, the or operator returns either the first true object or the last object. As with many other languages, evaluation stops as soon as a true expression is found for the or operator or as soon as a false expression is found for the and operator:
The == and!= operators test to see if their operands contains the same values. They are used in most situations. The is and is not operators test to see if their operands are the same object:
They reference the same object
< I x has been assigned to | a different object
Revisit "Nested lists and deep copies" (section 5.6) of "Lists, tuples, and sets" (chapter 5) if this example isn't clear to you.
Was this article helpful?