[Tutor] Re: Please critique my guessing game program.

Matt Smith smith-matt at tiscali.co.uk
Fri Jul 16 17:45:56 CEST 2004


Hi,
I've changed the program further to account for the help and suggestions
I've recieved.  I think this version is structured in a more logical way
and should also be impossible to crash through inputing the wrong answer. 
Please let me know what you think and if the program could be improved in
anyway.  I have greatly enjoyed writing my first Python program.

# A guessing game program.
# By Matt Smith

import random

def Random100():
    "Function to return a random number between 1 and 100"
    return random.randint(1,100)

def Get_int():
    "Function to collect an integer from the user"
    type_check = 0
    while type_check == 0:
        try:
            integer = int(raw_input())
	    type_check = 1
        except:
            print "Invalid input, try agin. ",
    return integer
    
# Main program.
# Introduce the program.

print "\n*****************"
print "* Guessing Game *"
print "*****************\n"

# Play the game.

playagainflag = 1
while playagainflag == 1:
    print "\nI am thinking of a number between 1 and 100"
    number = Random100()
    print "What's your first guess? ",
    guesses = 1
    guess = Get_int()
    while guess != number:
        if guess > number:
            print "Too high, try again. ",
	    guess = Get_int()
        else:
            print "Too low, try again. ",
	    guess = Get_int()
        guesses = guesses + 1
    print "Well done, you got it in",guesses,"goes.\n"
    playagain = raw_input("Do you want to play again? (y/n) ")
    if playagain == "y" or playagain == "Y":
        playagainflag = 1
    else:
        playagainflag = 0
print "Goodbye!\n"

# End of program.

Thanks again,
Matt.



More information about the Tutor mailing list