Game Development Reference
In-Depth Information
10 - Tic Tac Toe
'1 2 3 4 5 6 7 8 9'.split()
expression on the left side of or would return
False
as expected, and then we would evaluate the expression on the right side of the or
operator. But when we pass
'X'
(which would be the value in
move
) to the
int()
function,
int('X')
would give us an error. It gives us this error because the
int()
function can only take strings of number characters, like
'9'
or
'42'
, not strings like
'X'
As an example of this kind of error, try entering this into the shell:
>>> int('42')
42
>>> int('X')
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
int('X')
ValueError: invalid literal for int() with base
10: 'X'
But when you play our Tic Tac Toe game and try entering
'X'
in for your move, this
error doesn't happen. The reason is because the
while
loop's condition is being short-
circuited.
What short-circuiting means is that because the expression on the left side of the or
keyword (move not in
'1 2 3 4 5 6 7 8 9'.split()
) evaluates to
True
, the
Python interpreter knows that the entire expression will evaluate to
True
. It doesn't matter
if the expression on the right side of the
or
keyword evaluates to
True
or
False
, because
only one value on the side of the
or
operator needs to be
True
.
Think about it: The expression
True or False
evaluates to
True
and the expression
True or True
also evaluates to
True
. If the value on the left side is
True
, it doesn't
matter what the value is on the right side. So Python stops checking the rest of the
expression and doesn't even bother evaluating the
not isSpaceFree(board, int
(move))
part. This means the
int()
and the
isSpaceFree()
functions are never
called.
This works out well for us, because if the expression on the right side is
True
then
move
is not a string in number form. That would cause
int()
to give us an error. The
only times
move not in '1 2 3 4 5 6 7 8 9'.split()
evaluates to
False
are when
move
is not a single-digit string. In that case, the call to
int()
would not give
us an error.
An Example of Short-Circuit Evaluation
Here's a short program that gives a good example of short-circuiting. Open a new file in
the IDLE editor and type in this program, save it as
truefalsefizz.py
, then press F5 to run it.