Newbie help

Michael Hartl mhartl at post.harvard.edu
Sun Feb 13 22:33:38 EST 2005


You need to put the "You guessed it..." block inside a conditional (if
guess == number) so that it only executes if the guess is right.  (You
also need to break out of the loop in that case.)  As written, the "You
guessed it..." block executes the first time through the loop
regardless of the guess.  Also, if the initial guess is right, then the
while guess != number block never executes, and the message is never
displayed.

What you need is an infinite loop that breaks on a correct guess or
upon reaching the maximum number of tries.

Here's a corrected version:

# import random
#
# print "\tWelcome to 'Guess My Number'!"
# print "\nI'm thinking of a number between 1 and 100."
# print "You Only Have Five Guesses.\n"
#
# # set the initial values
# number = random.randrange(100) + 1
# guess = int(raw_input("Go Ahead and Take a guess: "))
# tries = 1
# max_tries = 5
#
# # guessing loop
# while True:
#     if guess == number:
#         # Guess is right!
#         print "You guessed it!  The number was", number
#         print "And it only took you", tries, "tries!\n"
#         break
#     elif tries == max_tries:
#         print "Sorry You Lose!!!!"
#         print "The Number was ", number
#         break
#     elif guess > number:
#         print "Guess Lower..."
#     elif guess < number:
#         print "Guess Higher..."
#     guess = int(raw_input("Take Another guess: "))
#     tries += 1
#
# raw_input("\n\nPress the enter key to exit.")

Michael

--
Michael D. Hartl, Ph.D.
Chief Technology Officer
http://quarksports.com/




More information about the Python-list mailing list