[Tutor] First Try 1.1

Alan Gauld alan.gauld at freenet.co.uk
Tue Feb 21 18:53:30 CET 2006


> I understand that the "else" is not neccessary for the program to work but 
> should I include it to show the end of the loop? I guess it's not 
> important in a program like this that has only 1 loop but maybe it makes 
> reading more complcated programs easier or is the indentation sufficient?

The indentation is fine, thats what its there for! :-)

> # create or replace lotto.txt in my home directory
> file('/home/mutt/lotto.txt','w').write('Here are your numbers:\n\n')

opening and closing(implicitly) the file each time is both slow and
expensive on computer resources. Just store the open file in a
variable like this:

output = file('/home/mutt/lotto.txt','w')
output.write('a first string\n')
output.write('a second string\n')
output.write('a final string\n')
output.close()

Note that you need to explicitly add the newline (\n) at the end
of each string. And explicitly closing the file is considered good
practice.

>    lotto_numbers = random.sample(xrange(1,46), 6)

You don't really need xrange, a simple range will suffice,
but it does no harm.

>    # append the numbers to lotto.txt
>    file('/home/mutt/lotto.txt','a').write('Game: ')
>    file('/home/mutt/lotto.txt','a').write(str(game))
>    file('/home/mutt/lotto.txt','a').write('    ')
>    file('/home/mutt/lotto.txt','a').write(str(lotto_numbers))
>    file('/home/mutt/lotto.txt','a').write('\n')

And you can use string forematting to create the string before writing:

info = "Game: %3d\t%3d\n" % (game, lotto_numbers)
output.write(info)

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list