Kevin said unto the world upon 2005-03-04 10:43:
Hello all. I have just completed my very first python program just a
simple number guessing. I would like for someone to try it out if they
could and let me know how I did with it and where I could have
improved apon it. There are t files main.py and defs.py

Thanks

Hi Kevin,

Though I am a learner, too, I have a few comments. They are more about style than substance.

1) A lot of your code comments get in the way of my reading and easily understanding the code. Consider:

.# leading `.'s to foil google groups and other whitespace stripping readers
.if play == '3': #If user picks 3
. print "\nHave a nice day!\n" #Tell them to have a nice day
. sys.exit() #Then exit the entire thing


I think this would be much easier to read if it were like:

.if play == '3':                        # If user picks 3
.    print "\nHave a nice day!\n"       # Tell them to have a nice day
.        sys.exit()                     # Then exit the entire thing

(Note that some people hate the comments along the side and would prefer them the precede the line(s) they comment on. I like the 2 column approach, but that's just one duffer's view.)

But, even better would be:

.if play == '3':
.    print "\nHave a nice day!\n"
.        sys.exit()

Your comments are close to the canonical example of 'bad comments':

count += 1  # increment count by 1

Comments like this add nothing except squiggles to read on the screen or page. They just repeat the code; so, instead of helping, they are just noise. Comments are good for tricky bits, to explain just why some non-obvious chunk of code is there, or to remind the reader (who could well be you) why some particular approach was taken.

(Neatness counts ;-)

2) Whitespace is a good thing. Python needs it horizontally, but you can (and, IMHO, should) employ vertical whitespace to chunk up the code. Your code had this chunk:

. if play == '3': #If user picks 3
. print "\nHave a nice day!\n" #Tell them to have a nice day
. sys.exit() #Then exit the entire thing
. elif play == '2': #If user picks 2
. instruct() #Then lets call the instructions function
. elif play == '1': #If user picks 1
. game() #Then lets call the game function for the user to play
. elif play == '': #This is used is the menu leaves the screen so the user can get it back
. choice() #Bring back the menu
. else:
. print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n"


Try reading that and then this:

. if play == '3':
. print "\nHave a nice day!\n"
. sys.exit()
.
. elif play == '2':
. instruct()
.
. elif play == '1':
. game()
.
. elif play == '': # I might have put a comment here but
. choice() # the else clause below explains it.
.
. else:
. print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n"


Which one is easier to read? :-)

The separation between blocks doesn't matter too much when the blocks are short, but I still like it. Different strokes, though. But, if each block had, say 4 or 5 lines, it would be much easier for me to parse with the separation.

3) I've come to like informative dosctrings a lot. When you start using tools like pydoc on your own code, you will be glad you used them. (Plus, they cut down on the need for inline comments.)

and,

4) I'd make the yesno() function do a bit more work. So, combining these two points, where you have:

.def yesno(question):
.    """Asks the use a yes or no question"""
.    answer = None
.    while answer not in ('y','ye','yes','n','no'):
.        answer = raw_input(question).lower()
.        if answer not in ('y','ye','yes','n','no'):
.            print "Please enter Y or N"
.    return answer

I have a utility function:

def yes_or_no(question):
.    '''Asks the user the question; returns True for yes, False for no.
.
.    question is used to prompt the user for raw_input. That input is
.    put in lower case and compared to the values ['y', 'yes', 'n',
.    'no']. If it matches a `yes' value, True is returned; if it
.    matches a `no' value False is returned. If it matches none of
.    these values, a report of what was entered and of valid inputs
.    is printed and the user is reprompted until an acceptable value
.    is entered.
.    '''
.    response = raw_input(question)
.    while True:
.
.        lresp = response.lower()
.
.        if lresp == 'y' or lresp == 'yes':
.            # adjust matching values to your tastes
.            return True
.        if lresp == 'n' or lresp == 'no':
.            return False
.
.        response = raw_input('''
.            You entered: %s
.            Valid inputs are `n', 'no', `y', and `yes' (any case).
.            Please try again.
.            %s
.            ''' %(response, question))

My code is a lot longer, but 1) it does a little bit more, and 2) it has a much more useful docstring. If you wanted to reuse your function elsewhere (and you will), you might have to actually look at the code to see how it works. Mine is much easier to use with help() or the web browser version of pydoc.

5) I don't see why you broke your program up the way you did. I would have everything but the yesno() in one file. The yesno I would put in something like the inpututils.py file I have where I've got other standard user input routines, too. (Examples would be code to ask for a number between n and m, any number, a file path, etc.)

Anyway, I hope that helps some and that the more experienced list members will swoop in (they always do :-) to fix anything I said that is goofy.

Best,

Brian vdB


##############################################################################

#!/usr/bin/python
#main.py
###########################
from defs import *
import sys
###########################

choice() #Lets call the main menu up for the user
#This is used to ask if you would like to keep playing#
while 1:
        play = raw_input("What is your choice? ") #Aks use to enter a choice
from the menu
        if play == '3': #If user picks 3
                print "\nHave a nice day!\n" #Tell them to have a nice day
                sys.exit() #Then exit the entire thing
        elif play == '2': #If user picks 2
                instruct() #Then lets call the instructions function
        elif play == '1': #If user picks 1
                game() #Then lets call the game function for the user to play
        elif play == '': #This is used is the menu leaves the screen so the
user can get it back
                choice() #Bring back the menu
        else:
                print "\nYou need to pick 1, 2 or 3 or hit enter to see 
choices\n"
#Let the user know that they can only pick 1, 2, 3 or just hit enter
and nothing else.

###########################################################################
#defs.py
#########
import random
import sys
#######################################################
#This is not used in the game yet
def yesno(question):
"""Asks the use a yes or no question"""
answer = None
while answer not in ('y','ye','yes','n','no'):
answer = raw_input(question).lower()
if answer not in ('y','ye','yes','n','no'):
print "Please enter Y or N"
return answer
########################################################
#This is the guessing game#
def game():
"""This is the main part of the guessing game"""
tries = 5 #Set the number of tries to 5
guess = random.randrange(2)+1 #Computer picks a number from 1 to 20
while 1:
try:
answer = int(raw_input("What is your guess? ")) #Ask the user to
guess the number
if answer != guess: #Check to see if answer is not equal to guessed number tries -= 1 #if answer is wrong reduce the number of tries by 1
print "Thats not it, you only have %d tries left" %tries #Tell
user not right answer
if tries == 0: #Check to see if user has run out of tries
print "\nYou lost this round!" #If no tries left let the user know
raw_input("\n[Hit Enter to Continue]\n") #Wait for user to go
back to main menu
choice() #Show main menu for user
break #Then break out of the loop
if answer == guess: #If the answer is equal to the guessed number
print "\nCongrats you just Won this round!!" #Tell the user he
just one in so many tries
raw_input("[Hit Enter to Continue]") #Wait for user to go back to main menu
choice() #Show main menu for user
break #Break out of the loop
except ValueError: #Lets make sure that the user is only typeing in
numbers and nothing else
print "\nYou can only use numbers\n" #Let user know they can only
use numbers


#This is the main menu for the game
def choice():
"""The main menu of the game"""
print """
########################################
# #
# NUMBER GUESSING GAME # # #
# - Created by Kevin J #
# - [EMAIL PROTECTED] #
# ------------------------------------ #
# 1 - Play #
# 2 - instructions #
# 3 - Quit #
########################################\n"""


#This is the instuctions on how to play the game that can be called
from the main menu
def instruct():
        """Instructions on how to play the
        guessing game"""
        print"""\n
                        HOW TO PLAY THE NUMBER GUESSING GAME
    ########################################################################
    # To play this game all you need to do is guess a number from 1 to 20. #
    # You will only have 5 tries to beat the game. Once you have beat the  #
    # game or you have used up all of your 5 tries you will be sent back   #
    # to the main screen were you can quit or start over again.            #
    ########################################################################
    [HIT ENTER FOR MAIN MENU]\n"""
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to