[Tutor] While Loop Help

Alan Gauld alan.gauld at btinternet.com
Thu Dec 11 11:20:23 CET 2014

On 11/12/14 04:20, Matthew Nappi wrote:

> (code pasted below); however if a player guesses the right number they
> still receive an ending message indicating that they failed.  How can I
> modify the code without using any advanced techniques to have a different
> message in the event of a successful guess?  Thanks in advance!

> 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")
> the_number = random.randint(1, 100)
> guess = int(input("Take a guess: "))
> tries = 1
> while guess != the_number and tries < 10:
>      if guess > the_number:
>          print("Lower...")
>      elif guess < the_number:
>          print("Higher...")
>      else:
>          print("You win.")
>      guess = int(input("Take a guess: "))
>      tries += 1

So far so good, except that you probably don;t want
the winner to have to input another number after
being told he already won.

You can avoid that by making the initial value for
guess be something invalid, then move the input
line to the top of the while loop:

guess = 0

while guess != the_number and tries < 10:
     guess = int(input("Take a guess: "))
     tries += 1
     ... the if/else code here.

> print("You fail!  The number was", the_number)

But you always print this regardless of the result.
You need to put a test around it to check whether
the guess equals the number and only print this
if it is not.

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list