[Tutor] While Loop Help

Steven D'Aprano steve at pearwood.info
Thu Dec 11 12:39:57 CET 2014


On Wed, Dec 10, 2014 at 11:20:12PM -0500, Matthew Nappi wrote:

> I am working on the challenges from “Python Programming for the Absolute
> Beginner” Chapter 3.  I am asked to modify the original code pasted below
> to limit the number of guesses a player has to guess the number.  I did so
> (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!

[...]
> *My Modified Code:*

> 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 < 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


Follow the code: start at the top of the while loop. The next thing that 
happens is that the computer checks whether guess > the number, 
otherwise whether guess < the number, otherwise they must be equal. 
Whichever one happens, a message is printed. What happens next?

The next line executes, which says "take a guess". That isn't right, 
since that forces the player to guess even after they've won.

There are a few ways to deal with that. One way would be to change the 
while loop to something like this:


the_number = random.randint(1, 100)
guess = -999999   # Guaranteed to not equal the_number.
tries = 0  # Haven't guessed yet.
while guess != the_number and and tries < 10:
    tries += 1
    guess = int(input("Take a guess: "))
    if guess < the_number:
        print("too low")
    elif guess > the_number:
        print("too high")
    else:
        print("you win!")


Notice how this differs from the earlier version? Instead of asking the 
player to guess at the *end* of the loop, after checking whether the 
guess was right, you ask the player to guess at the *start* of the loop. 
That means you don't need an extra guess at the beginning, and it means 
you don't get an extra, unneeded guess even after you win.

Now let's move on to the next line:

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

This line *always prints*, regardless of whether you have won or not. 
The easiest way to fix that is to just check whether or not the player 
guessed correctly:

if guess != the_number:
    print("You fail!  The number was", the_number)


-- 
Steven


More information about the Tutor mailing list