[Tutor] Guess my number game

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Dec 7 15:16:19 CET 2013


On 06/12/2013 23:34, Lelani Slabber wrote:
> Hi,
> I am learning Python witht Python for beginners book by Michael Lawson
> and have trouble with one task in chapter 3 - challenge 3.
> I have to add code so the user has a limited number of tries - in this
> case I have set it to less than 5 in the while loop and I want the
> program to stop if the tries are equal to 5.  I get an invalid syntax
> error.  Please help.
> # 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.randint(1, 100)
> guess = int(input("Take a guess: "))
> tries = 1
> # guessing loop
> while (guess != the_number) and (tries <5):
>      if guess == the_number:
>          print("You guessed it")
>
>      else:
>          if guess > the_number:
>              tries=tries +1
>              print("Higher...")
>              guess = int(input("Take a guess: "))
>          else:
>              tries=tries+1
>              print("too low")
>              guess = int(input("Take a guess: "))
>              else:

Telling us where you got the syntax error often helps :)  But in this 
case I'd hazard a guess that it's in the line above.  I'll leave you to 
restructure your code as you see fit as part of your learning curve.

>                  if tries == 5:
>                      break
>
> print("You guessed it!  The number was", the_number)
> print("And it only took you", tries, "tries!\n")
>
> input("\n\nPress the enter key to exit.")
>

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list