[Tutor] while loops

Dave Angel d at davea.name
Thu Dec 15 00:03:51 CET 2011


On 12/14/2011 05:41 PM, rog capp wrote:
> # 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 to high, to low
> # or right on the money
>
> import random
>
> print("\tWelcome to 'Guess My Number'!")
> print("I'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:
>
>      if guess>  the_number:
>          print("Lowere...")
>      else:
>          print("Higher...")
>
>      guess = int(input("Take a guess: "))
>      tries += 1
>
> print("good job")
>
> input("\n\nPress the enter key to exit.")
>
>
>
> This is a program from "Python for the absulute beginner(which I am).
> End of the chapter is a challenge that asks me to limit the number of
> guesses the player gets.
> If he/she fails to guess the number after a certain number of attempts
> then it displays a message
> about his failure.It needs to be a while loop cause it the topic I'm
> at.Can anyone give me some help
> on where to put the loop.When i put it in with the "if
> guess>the_number" loop, the program either
> prints higher or lower continuously(continuous loop I imagine) or it
> gives me the answer whether its
> right or wrong after a couple guesses.Any help will be appreciated.
> _
You already have a while-loop.  So add another condition to it:
        while guess != answer   and tries< 10:

then outside the loop, write an if-test conditional on whether guess == 
number

If so, tell him good job, if not, tell him he took too many tries.

-- 

DaveA



More information about the Tutor mailing list