Game Development Reference
In-Depth Information
6 - Dragon Realm
Boolean Operators
Boolean logic deals with things that are either true or false. This is why the boolean data
type only has two values,
True
and
False
. Boolean statements are always either true or
false. If the statement is not true, then it is false. And if the statement is not false, then it is
true.
Boolean operators compare two different boolean values and evaluate to a single boolean
value. Do you remember how the
*
operator will combine two integer values and produce a
new integer value (the product of the two original integers)? And do you also remember
how the
+
operator can combine two strings and produce a new string value (the
concatenation of the two original strings)? The
and
boolean operator combines two
boolean values to produce a new boolean value. Here's how the
and
operator works.
Think of the sentence, "Cats have whiskers and dogs have tails." This sentence is true,
because "cats have whiskers" is true and "dogs have tails" is also true.
But the sentence, "Cats have whiskers and dogs have wings." would be false. Even
though "cats have whiskers" is true, dogs do not have wings, so "dogs have wings" is false.
The entire sentence is only true if both parts are true because the two parts are connected by
the word "and." If one or both parts are false, then the entire sentence is false.
The
and
operator in Python works this way too. If the boolean values on both sides of
the
and
keyword are
True
, then the expression with the and operator evaluates to
True
.
If either of the boolean values are
False
, or both of the boolean values are
False
, then
the expression evaluates to
False
.
Evaluating an Expression That Contains Boolean Operators
So let's look at line 13 again:
13. while cave != '1' and cave != '2':
This condition is made up of two expressions connected by the
and
boolean operator.
We first evaluate these expressions to get their boolean (that is,
True
or
False
) values.
Then we evaluate the boolean values with the
and
operator.
The string value stored in cave when we first execute this while statement is the blank
string,
''
. The blank string does not equal the string
'1'
, so the left side evaluates to
True
. The blank string also does not equal the string
'2'
, so the right side evaluates to
True
. So the condition then turns into
True and True
. Because both boolean values
are
True
, the condition finally evaluates to
True
. And because the while statement's
condition is
True
, the program execution enters the while-block.