In this second part of a six-part series that explores the Python programming language, we will continue the discussion we started last week on its logical operators. This article is excerpted from chapter two of the book Beginning Game Development with Python and Pygame: From Novice to Professional, written by Will McGugan (Apress; ISBN: 9781590598726).
Or Operator
To complement theand operator, we have theoroperator, which results inTrueif either the first or second value isTrue. Let’s say we want to eat fugu if it is tasty or it is very cheap (after all, who can turn down cheap fugu?):
if fugu == "tasty" or price < 20.0: print "Eat the fugu!"
Just like theandoperator, theor operator has plenty of applications in real life. My car will stop if I run out of gas or the battery goes dead. See Table 2-2 for theor truth table.
Table 2-2. Truth Table for the Or Operator
Logic False or False
Result False
True or False
True
False or True
True
True or True
True
Not Operator
The final logic operator we will look at is thenotoperator, which swaps the state of a boolean value, soTruebecomesFalse andFalse becomesTrue(see Table 2-3). You can use this to reverse any condition:
if not (fugu == "tasty" and price < 100.0): print "Don't eat the fugu!"
Here we have reversed thefugu == "tasty" and price < 100.0condition so that Python runs the code block only if the condition is not true (that is, false).