Game Development Reference
In-Depth Information
10 - Tic Tac Toe
This small program has two functions: TrueFizz() and FalseFizz() . TrueFizz
() will display a message and return the value True , while FalseFizz() will display a
message and return the value False . This will help us determine when these functions are
being called, or when these functions are being skipped due to short-circuiting.
The First if Statement (Cats and Dogs)
The first if statement on line 9 in our small program will first evaluate TrueFizz() .
We know this happens because Cats is printed to the screen (on line A in the output). The
entire expression could still be True if the expression to the right of the or keyword is
True . So the call TrueFizz('Dogs') one line 9 is evaluated, Dogs is printed to the
screen (on line B in the output) and True is returned. On line 9, the if statement's
condition evaluates to False or True , which in turn evaluates to True . Step 1 is then
printed to the screen. No short-circuiting took place for this expression's evaluation.
The Second if Statement (Hello and Goodbye)
The second if statement on line 12 also has short-circuiting. This is because when we call
TrueFizz('Hello') on line 12, it prints Hello (see line D in the output) and returns
True . Because it doesn't matter what is on the right side of the or keyword, the Python
interpreter doesn't call TrueFizz('Goodbye') . You can tell it is not called because
Goodbye is not printed to the screen. The if statement's condition is True , so Step 2 is
printed to the screen on line E.
The Third if Statement (Spam and Cheese)
The third if statement on line 15 does not have short-circuiting. The call to TrueFizz
('Spam') returns True , but we do not know if the entire condition is True or False
because of the and operator. So Python will call TrueFizz('Cheese') , which prints
Cheese and returns True . The if statement's condition is evaluated to True and
True , which in turn evaluates to True . Because the condition is True , Step 3 is printed
to the screen on line H.
The Fourth if Statement (Red and Blue)
The fourth if statement on line 18 does have short-circuiting. The FalseFizz
('Red') call prints Red on line I in the output and returns False . Because the left side
of the and keyword is False , it does not matter if the right side is True or False , the
condition will evaluate to False anyway. So TrueFizz('Blue') is not called and
Blue does not appear on the screen. Because the if statement's condition evaluated to
False , Step 4 is also not printed to the screen.
Short-circuiting can happen for any expression that includes the Boolean operators and
and or . It is important to remember that this can happen; otherwise you may find that some
function calls in the expression are never called and you will not understand why.
Search WWH ::




Custom Search