Submitted by jean-paul on Sat, 09/29/2012 - 01:40

Here is a small example showing how choosing good variable names can make a huge difference. Look at the following code block, and see how long it takes you to work out what it does. If you find it takes you a while, look at the improved code below that and see how much easier it is! Even with short variables that are words, not being descriptive makes debugging very difficult. Using letters on their own is frequently worse. Both code blocks are functionally identical, only variable names are changed.

 
import random
 
def brooms(hit):
    dig = hit+1
    while dig > hit or dig < 1:
        dig = int((str((random.random()*10)+0.5))[0])
    return dig
 
def monkey(cat,run):
    dodges = 0
    play = 1
    while dodges < run:
        red = brooms(cat)
        dodges += red
        print 'Loop:',str(play),'Roll:',str(red),'Sum: ',str(dodges)
        play += 1
 
monkey(6,100)
.
 
.
 
.
 
.
 
Now for the fixed up code:
 
import random
 
def dice_roll(sides):
    roll = sides+1
    while roll > sides or roll < 1:
        roll = int((str((random.random()*10)+0.5))[0])
    return roll
 
def rolls_until(sides,sum_until):
    running_total = 0
    loop_count = 1
    while running_total < sum_until:
        current_roll = dice_roll(sides)
        running_total += current_roll
        print 'Loop:',str(loop_count),'Roll:',str(current_roll),'Sum: ',str(running_total)
        loop_count += 1
 
rolls_until(6,100)