Re: [Tutor] First Try 1.2
Hi John, Its developing nicely so I'll add some more style issue comments :-) 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') I'd move the middle comment up with the one above. Think of a block of comments commenting on a paragraph of code, rather than dealing in single lines: # store the /home/mutt/lotto.txt in f # create or replace lotto.txt in my home directory f = file('/home/mutt/lotto.txt','w') f.write('Here are your numbers:\n\n') Now the code is easier sepsarated from the comment. BUT, is the comment really needed, after all the explicit pathname shows whgere it is going and the variable tells us where we are storing it. How much of: f = file('/home/mutt/lotto.txt','w') f.write('Here are your numbers:\n\n') will be hard to understand if you come back in a few months? Comments are best used to explain the *why* of code and let good variable names and structure describe the how. A concept often called Self documenting code # 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) ') how_many_games = int(raw_input('How many games you would like generated? ')) number_of_balls = int(raw_input('\nHow many balls are in the lotto you wish to play? ')) how_many_numbers = int(raw_input('\nHow many numbers you would like per game? ')) chk_pwrball = raw_input('Is there a power ball? (y/n) ') Again comparing these two do the comments add much more information than the variable names do? And by removing them the code itself becomesa much more obvious and readable. print '\n\nHere are your numbers : \n' # loop for the number of games selected by user for game in range(1, how_many_games + 1): # 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) lotto_numbers.sort() if chk_pwrball == 'n': # Right justified in 3 character width then a tab (\t) then a blank line (\n) print '%3s\t%s\n' % (game, lotto_numbers) # write the numbers to lotto.txt save_numbers = 'Game: %3s\t%3s\n' % (game, lotto_numbers) f.write(save_numbers) The commenting in this section is better spaced but again mostly just says what the code does. The comment explaining the string format is probably the most valid comment in the program, it describes what the format is trying to accomplish which is valid since format strings are not self evident. if chk_pwrball == 'y': pwrball = random.sample(range(1,number_of_balls +1), 1) print '%3s\t%s \tPower Ball: %s\n' % (game, lotto_numbers, pwrball) save_numbers = 'Game: %3s\t%s \tPower Ball: %s\n' % (game, lotto_numbers, pwrball) f.write(save_numbers) print '\nHope you win!' f.write('\nHope you win!') f.close() And interesting that you (coprrectly) chose not to comment this sectoon at all Don't take these comments too personally but it is just a classic case of how you have improved the code clarity to the point where the comments, which were originally necessary, are now superfluous! This is a common mistake for beginners so I thought I'd take the opportunity to highlight the issue: Comments are useful but clearly written code is much better Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First Try 1.2
G'day, Added a power ball option to the lotto program today. The program does way more then I ever intended when I started it so I'll try a new project. Maybe I'll come back to it when I try out Tkinter and try to give it a GUI. Anywayhere's my latest effort. 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') # 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) ') print '\n\nHere are your numbers : \n' # loop for the number of games selected by user for game in range(1, how_many_games + 1): # 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) lotto_numbers.sort() if chk_pwrball == 'n': # Right justified in 3 character width then a tab (\t) then a blank line (\n) print '%3s\t%s\n' % (game, lotto_numbers) # write the numbers to lotto.txt save_numbers = 'Game: %3s\t%3s\n' % (game, lotto_numbers) f.write(save_numbers) if chk_pwrball == 'y': pwrball = random.sample(range(1,number_of_balls +1), 1) print '%3s\t%s \tPower Ball: %s\n' % (game, lotto_numbers, pwrball) save_numbers = 'Game: %3s\t%s \tPower Ball: %s\n' % (game, lotto_numbers, pwrball) f.write(save_numbers) print '\nHope you win!' f.write('\nHope you win!') f.close() John _ Shopping made easy @ tradingpost.com.au http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fwww%2Etradingpost%2Ecom%2Eau%2F%3Freferrer%3DnmsnHMetagv1_t=753082530_r=emailtagline_m=EXT ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First Try 1.2
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First Try 1.1
John Connors wrote: 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? 'else' in a for loop has a very specific meaning and usage - the else clause is executed only if the for loop completes normally, without executing a break statement. This is useful when you have a loop that is searching for some condition, and you want to execute some default code if the condition is never met. For example, a simple loop to search a list for a value and print a result could look like this (note: this is NOT the best way to solve this problem, it is just a simple example of for / else): def search(value, lst): ... for item in lst: ... if value == item: ... print 'Found', value ... break ... else: ... print value, 'not found' ... lst = range(10) search(3, lst) Found 3 search(11, lst) 11 not found for / else is very handy in this situation and should not be used just to show that the loop is over. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] First Try 1.2
G'day :) I've added a little more to the program. It now sorts the game numbers from lowest to highest which makes filling out the tickets a lot easier, I've been putting off doing this because I wasn't sure how to go about it but once I started looking I found python does it all for me with .sort() Also added some extra user input so different types of lotto games can be played. Found a glaring bug...the program didn't pick the winning numbers for me and I'm now $6 poorer! g Next on the to do list is add an option for a power ball, I actually did this tonight but I had 'if' statements all over the place. Which made the code unreadable so I'm going to work on a different way of doing it. I hope posting my efforts in here is ok. I learnt a lot after posting the first version of it but if I'm doing the wrong thing please tell me and I'll desist. import random # create or replace lotto.txt in my home directory file('/home/mutt/lotto.txt','w').write('Here are your numbers:\n\n') # 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? ')) print '\n\nHere are your numbers : \n' # loop for the number of games selected by user for game in range(1, how_many_games + 1): # generate 6 random numbers between 1 and 45 inclusive lotto_numbers = random.sample(xrange(1,number_of_balls + 1), how_many_numbers) lotto_numbers.sort() # Right justified in 3 character width then a tab (\t) then a blank line (\n) print '%3s\t%s\n' % (game, lotto_numbers) # 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') print '\nHope you win!' file('/home/mutt/lotto.txt','a').write('\n\nHope you win!') John _ Search for local singles online @ Lavalife - Click here http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom%2Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26locale%3Den%5FAU%26a%3D21550_t=21550_r=endtext_m=EXT ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First Try 1.1
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] First Try 1.1
G'day, Thanks for the input on my lotto number selector program, very much appreciated and I learnt a lot. I've (hopefully) cleaned it up a little, and expanded it to write the numbers to a text file. I'm sure there must be a better way of doing it then the way I have. 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? import random # create or replace lotto.txt in my home directory file('/home/mutt/lotto.txt','w').write('Here are your numbers:\n\n') # user input for number of games to choose how_many_games = int(raw_input('Enter how many games you would like generated : ')) print '\n\nHere are your numbers : \n' # loop for the number of games selected by user for game in range(1, how_many_games + 1): # generate 6 random numbers between 1 and 45 inclusive lotto_numbers = random.sample(xrange(1,46), 6) # Right justified in 3 character width then a tab (\t) then a blank line (\n) print '%3s\t%s\n' % (game, lotto_numbers) # 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') print '\nHope you win!' file('/home/mutt/lotto.txt','a').write('\n\nHope you win!') John _ New year, new job there's more than 100,00 jobs at SEEK http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fninemsn%2Eseek%2Ecom%2Eau_t=752315885_r=Jan05_tagline_m=EXT ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] First Try
G'day :) 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, 6 numbers between 1 and 44 (inclusive). I had done this many years before in basic and I thought back then it would be a simple task but I struck a problem of the random number generator repeating numbers occasionally so I had to check each number against the other and generate another random number if there were duplicates. 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. I decided to make it a little more user friendly and allow the user to pick home many games they want generated. Then I made the output a little easier to read with a few blank lines. Here is what I came up with: import random numberof = int(raw_input('Enter how many games you would like generated :')) #user input for number of games to choose print print print Here are your numbers : print for games in range(1, numberof + 1): #loop for the number of games selected by user lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers between 1 and 44 inclusive print games, lotto print else: print print Hope you win! I know this is a very simple program but... could I have done this a better way? John _ Search for local singles online @ Lavalife - Click here http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom%2Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26locale%3Den%5FAU%26a%3D21550_t=21550_r=endtext_m=EXT ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First Try
Nice Job John. I made a few comments below on a few things I noticed. On Sunday 19 February 2006 05:33, John Connors wrote: G'day :) 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, 6 numbers between 1 and 44 (inclusive). I had done this many years before in basic and I thought back then it would be a simple task but I struck a problem of the random number generator repeating numbers occasionally so I had to check each number against the other and generate another random number if there were duplicates. 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. I decided to make it a little more user friendly and allow the user to pick home many games they want generated. Then I made the output a little easier to read with a few blank lines. Here is what I came up with: import random numberof = int(raw_input('Enter how many games you would like generated :')) #user input for number of games to choose 10,000 lines of code or 6months later (whichever comes first...) will you remember what numberof represents? Number of times the cow jumped over the moon? I try not to end a var with a prep (and will usually just omit it). I would personally go for num_games_wanted or num_tickets. (Actually to tell the truth I am a mixedCase kinda guy so would really go for numGamesWanted or numTickets, but that is not really PEP 8 [1] friendly so I am trying to break my ways.) print print print Here are your numbers : print If you desire you can use \n for return to reduce this all into one line: print \n\n\Here are your numbers :\n\n No big deal. for games in range(1, numberof + 1): #loop for the number of games selected by user lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers between 1 and 44 inclusive print games, lotto print else: print print Hope you win! You don't need an else block (you will always enter it, ). You can just do: for games in range(1,numberof + 1): lotto = random.sample(xrange(1,45),6) print games, lotto print print \nHope you win! I know this is a very simple program but... could I have done this a better way? Looks pretty good to me. If you want to expand this a little more you can try: 1.) Assign all the lottery tickets to a variable and then print out the lottery tickets after you have them all. ( A list would be helpful here...) 2.) Break your program into functions so that you can do something like: (num_tickets_wanted, min_num, max_num) = get_user_input() lotto_tickets=generate_tickets(num_tickets_wanted, min_num,max_num) print_results(lotto_tickets) NOTE: It would be pure evil to drop that alll into one line. print_results(generate_tickets(get_user_input())) I shouldn't have even mentioned that, but you get the idea. John _ Search for local singles online @ Lavalife - Click here http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom%2 Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26locale%3 Den%5FAU%26a%3D21550_t=21550_r=endtext_m=EXT ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Have some fun with itat least until you win the lottery. --Todd Maynard -- Computers are unreliable, but humans are even more unreliable. Any system which depends on human reliability is unreliable. -- Gilb ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First Try
and for a belated footnote: [1] = http://www.python.org/peps/pep-0008.html Style Guide for python code. --Todd On Sunday 19 February 2006 06:27, Todd Maynard wrote: Nice Job John. I made a few comments below on a few things I noticed. On Sunday 19 February 2006 05:33, John Connors wrote: G'day :) 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, 6 numbers between 1 and 44 (inclusive). I had done this many years before in basic and I thought back then it would be a simple task but I struck a problem of the random number generator repeating numbers occasionally so I had to check each number against the other and generate another random number if there were duplicates. 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. I decided to make it a little more user friendly and allow the user to pick home many games they want generated. Then I made the output a little easier to read with a few blank lines. Here is what I came up with: import random numberof = int(raw_input('Enter how many games you would like generated :')) #user input for number of games to choose 10,000 lines of code or 6months later (whichever comes first...) will you remember what numberof represents? Number of times the cow jumped over the moon? I try not to end a var with a prep (and will usually just omit it). I would personally go for num_games_wanted or num_tickets. (Actually to tell the truth I am a mixedCase kinda guy so would really go for numGamesWanted or numTickets, but that is not really PEP 8 [1] friendly so I am trying to break my ways.) print print print Here are your numbers : print If you desire you can use \n for return to reduce this all into one line: print \n\n\Here are your numbers :\n\n No big deal. for games in range(1, numberof + 1): #loop for the number of games selected by user lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers between 1 and 44 inclusive print games, lotto print else: print print Hope you win! You don't need an else block (you will always enter it, ). You can just do: for games in range(1,numberof + 1): lotto = random.sample(xrange(1,45),6) print games, lotto print print \nHope you win! I know this is a very simple program but... could I have done this a better way? Looks pretty good to me. If you want to expand this a little more you can try: 1.) Assign all the lottery tickets to a variable and then print out the lottery tickets after you have them all. ( A list would be helpful here...) 2.) Break your program into functions so that you can do something like: (num_tickets_wanted, min_num, max_num) = get_user_input() lotto_tickets=generate_tickets(num_tickets_wanted, min_num,max_num) print_results(lotto_tickets) NOTE: It would be pure evil to drop that alll into one line. print_results(generate_tickets(get_user_input())) I shouldn't have even mentioned that, but you get the idea. John _ Search for local singles online @ Lavalife - Click here http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom %2 Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26local e%3 Den%5FAU%26a%3D21550_t=21550_r=endtext_m=EXT ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Have some fun with itat least until you win the lottery. --Todd Maynard ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First Try
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor