8. Your own while/else



How do I remove the "guess again" from being printed again after the third guess has been entered?
It goes:
Your guess: 1
Guess again.
Your guess: 2
Guess again.
Your guess: 3
Guess again <<< I want this guess again not to appear

from random import randint

# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)

guesses_left = 3
# Start your game!
while guesses_left > 0:
    guess = int(raw_input("Your guess: "))
    if guess == random_number:
        print "You win!"
        print "Guess again!"
        guesses_left -= 1
    print "You lose."


There are two ways, essentially. One is to write a condition that wraps the print statement.

guesses_left -= 1
if guesses_left: print "Guess again!"

The other way is a little more dramatic...

prompt = "Your guess: "
while ....:
    guess = int(raw_input(prompt))
    if ...:

        prompt = "Guess again! "
        guesses_left -= 1


With the first condition, where would I insert it in the code?


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.