Game Development Reference
In-Depth Information
7 - Using the Debugger
coinFlips.py
This code can be downloaded from http://inventwithpython.com/coinFlips.py
If you get errors after typing this code in, compare it to the topic's code with the online
diff tool at http://inventwithpython.com/diff or email the author at
al@inventwithpython.com
1. import random
2. print('I will flip a coin 1000 times. Guess how many
times it will come up heads. (Press enter to begin)')
3. input()
4. flips = 0
5. heads = 0
6. while flips < 1000:
7. if random.randint(0, 1) == 1:
8. heads = heads + 1
9. flips = flips + 1
10.
11. if flips == 900:
12. print('900 flips and there have been ' + str
(heads) + ' heads.')
13. if flips == 100:
14. print('At 100 tosses, heads has come up ' + str
(heads) + ' times so far.')
15. if flips == 500:
16. print('Half way done, and heads has come up ' +
str(heads) + ' times.')
17.
18. print()
19. print('Out of 1000 coin tosses, heads came up ' + str
(heads) + ' times!')
20. print('Were you close?')
The program runs pretty fast. It probably spent more time waiting for the user to press
the Enter key than it did doing the coin flips. Lets say we wanted to see it do coin flips one
by one. On the interactive shell's window, click on Debug and then Debugger at the top
menu to bring up the Debug Control window. Then press F5 to run the program.
The program starts in the debugger on line 1. Press Step three times in the Debug Control
window to execute the first three lines. You'll notice the buttons become disabled because
the input() function has been called and the interactive shell window is waiting for the
player to type something. Click on the interactive shell window and press Enter. (Be sure to
click beneath the text in the shell window, otherwise IDLE might not receive your
keystrokes.) After entering text for the input() call, the Step buttons will become
enabled again.
You can click Step a few more times, but you'll find that it would take quite a while to
get through the entire program. Instead, set a break point on lines 12, 14, and 16 (Figure 7-
6).
Search WWH ::




Custom Search