[Tutor] First Try
Alan Gauld
alan.gauld at freenet.co.uk
Sun Feb 19 16:54:28 CET 2006
> I started getting sick of reading tutorials so for a bit of a break I set
> myself the task of writing a program to pick lotto numbers,
Thats always a good idea! :-)
Sometimes you discover you don't know enough to finish it
but you can always go back, but in this case....
> So I was prepared for the same problem with python but I found that python
> takes care of that for me so the program would only have to be one line.
Yep, thats a common "problem" with Python, you start with what sounds
an interesting challenge only to discover that Python makes it trivially
easy! (Of course sometimes the trivially easy turns out to be astonishingly
hard!)
Now for some very nit-picking style stuff...
> import random
>
> numberof = int(raw_input('Enter how many games you would like generated
> :')) #user input for number of games to choose
Its traditional to put comments above the lines to which they refer.
> print
> print
> print "Here are your numbers :"
> print
print '\n\nHere are your numbers : \n"
\n is a newline.
Or
print '''
Here are your numbers :
'''
Triple quotes allow newlines wiothin them.
> for games in range(1, numberof + 1): #loop for the number of games
> selected
games is plural so implies some kind of collection or sequence, the
singular form is more suitable here since its really a single game number
that it holds
> lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers
> between 1 and 44 inclusive
> print games, lotto
> print
I'd probably use some string formatting here to ensure a neat layout:
print "%3s\t%s" % (game, lotto)
That will print a number right justified in 3 character width then a tab(\t)
followed by the list.
> else:
> print
> print "Hope you win!"
You don't need the else, you always want to print that at the end
of the loop so just have it as part of the text.
Its very rare to use the else part of a for loop. In fact I've never used
it for anything real so far as I can recall!
> I know this is a very simple program but... could I have done this a
> better way?
The technique is fine, the points above are really about style and
therefore something of a matter of personal taste.
One other technique you could have used is list comprehension
(you probably haven't met those yet) which could have produced all
of your output in one go then you would only need to print it. But
the advantage in minimal.
One enhancement you might like to try is to ask for an optional
lucky number and only display sequences with the lucky number
in (Hint: there is a very easy way to do this and there is a much harder
way).
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