[Tutor] First Try 1.2
Kent Johnson
kent37 at tds.net
Wed Feb 22 12:00:06 CET 2006
John Connors wrote:
> import random
>
> # store the /home/mutt/lotto.txt in f
> f = file('/home/mutt/lotto.txt','w')
> # create or replace lotto.txt in my home directory
> f.write('Here are your numbers:\n\n')
>
The comments don't really add anything to the program. Comments that
restate exactly what the code is doing are not that helpful. The code
should be clear by itself. As a beginner they may seem like a helpful
crutch but you will get better at reading the code.
For example,
how_many_games = int(raw_input('How many games you would like generated? '))
is well-written and expressive. With the helpful variable name and the
input prompt it's pretty easy to figure out what it does. Adding the comment
# user input for number of games to generate
actually obscures the code without adding to its comprehensibility.
A better choice might be to have one comment for the whole block of user
input code, something like
# Get required user input
Good comments describe the code at a higher level than the code itself,
or explain tricky bits. Comments that give a blow-by-blow account of the
code just get in the way.
I will often break my code into small chunks with a comment before each
chunk that says what it does. Then it is very easy to skim the code and
skip sections I'm not interested in.
> # user input for number of games to generate
> how_many_games = int(raw_input('How many games you would like generated? '))
> # user input for number of balls (to allow different lotto games)
> number_of_balls = int(raw_input('\nHow many balls are in the lotto you wish
> to play? '))
> # user input for how many numbers per game (to allow systems entries)
> how_many_numbers = int(raw_input('\nHow many numbers you would like per
> game? '))
> # check if there is a power ball
> chk_pwrball = raw_input('Is there a power ball? (y/n) ')
Here is another reason why it is a bad idea to just describe the code in
the comments - often the code changes and the comment doesn't. Now you
have an inaccurate comment which is worse than no comment at all.
> # generate 6 random numbers between 1 and 45 inclusive then sort them
> lotto_numbers = random.sample(range(1,number_of_balls + 1),
> how_many_numbers)
> print '\nHope you win!'
Good luck!
Kent
More information about the Tutor
mailing list