# CS2/examples/objects/OhNo.py David MacQuigg 11-Sept-07 '''Test a biased coin, doing everything wrong programwise. Horrify your professor, but at least get the right answer!''' bias = 0.2 # useless comment numTrials = 500 totalHeads = 0 loopIndex = 0 while loopIndex < numTrials: loopIndex = loopIndex + 1 # Add 1 to loopIndex (more gradoo) from random import random if random() < bias: print 'H', totalHeads = totalHeads + 1 else: print '-', print # a new line percentHeads = 100 * totalHeads/numTrials format = "totalHeads = %5s\npercentHeads = %5.1F" print format % (totalHeads, percentHeads) ''' So what is wrong with this program? 1) Complete lack of functions, classes, or any modern program structure means the program does one thing only. You have to edit and re-run the whole program to do something else. 2) No useful comments means that later the program will be hard to understand. 3) No unit tests means later modifications may break existing code. A mod may seem to work, and you won't know if earlier code is still OK. 4) Loop indices are ugly. Study the syntax of Python's "for" statement. 5) "import" statement buried in the program makes it hard to see what modules this module depends on. At least get that import statement out of the loop. We don't need to import a module 500 times! 6) "print" statements embedded in the logic means little flexibility for different displays. 7) Maybe this doesn't matter, but percentHeads should probably be a float. The formula above is correct, but it depends on subtleties of operator precedence to avoid gross error. If you really want an integer result, at least make clear your intent. (100 * totalHeads) // numTrials ~'''