Greeting! I'm learning Python through the book "Python Programming, Second Edition for the absolute beginner" by Michael Dawson. In it, he has the program "Guess my number" (code pasted below). His challenge is to modify the code so that there are only a limited number of attempts before the program exits with a chastising message.
Try as I may, I cannot seem to get the syntax correct for nested while loops. I was able to do it with two separate if statements, but this seems very unelegant to me. Could you provide a way to achieve this using nested while statements, or suggest a better use of the ifs? Also, while asking for help from this forum: for short pieces of code such as these, is it appropriate to enter them as inline text, or is it preferred to have them as attachments? I presume for long pieces of code the latter applies. Thank you Paul Peterson Ellicott, Colorado The Technological Capital of Mid Central Eastern El Paso County, Colorado.
# Guess My Number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." print "Try to guess it in as few attempts as possible.\n" # set the initial values the_number = random.randrange(100) + 1 guess = int(raw_input("Take a guess: ")) tries = 1 # guessing loop while (guess != the_number): if tries < 5: if (guess > the_number): print "Lower..." else: print "Higher..." guess = int(raw_input("Take a guess: ")) tries += 1 else: break if tries < 5: print "You guessed it! The number was", the_number print "And it only took you", tries, "tries!\n" else: print "You have exceeded your attempts." raw_input("\n\nPress the enter key to exit.")
# Guess My Number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." print "Try to guess it in as few attempts as possible.\n" # set the initial values the_number = random.randrange(100) + 1 guess = int(raw_input("Take a guess: ")) tries = 1 # guessing loop while (guess != the_number): if (guess > the_number): print "Lower..." else: print "Higher..." guess = int(raw_input("Take a guess: ")) tries += 1 print "You guessed it! The number was", the_number print "And it only took you", tries, "tries!\n" raw_input("\n\nPress the enter key to exit.")
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor