I'm a python noob and I'm getting to grips with python via 'Python Programming for the Absolute Beginner (2nd Edition - Python 2.3, but I'm using 2.7)'.
The book presents challenges to complete and I'm having trouble getting my head round one of them; any help would be greatly appreciated as I want to get my head around this before I move on.
Chapter 3, Challenge 3 - Guess My Number: Modify the code below to limit the number of tries a player has to guess the number.
How would I go about doing this? The attempts I've made so far to set a variable, have all ended with the answer being revealed whether the user gets the answer right or not. Thanks in advance guys.
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.")
So far, I've attempted the following unsuccessfully.
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
limit = 8
# guessing loop
while (guess != the_number and tries < limit):
if (guess > the_number):
print "Lower..."
elif (guess < the_number):
print "Higher..."
else:
print "You've used all " + limit -1 +"of your attempts \
and didn't get the right answer. Shame on You!"
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.")