8. Your own while/else


#1



https://www.codecademy.com/en/courses/python-beginner-en-cxMGf/0/8?curriculum_id=4f89dab3d788890003000096


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!"
        break
        
    else:
        print "Guess again!"
        guesses_left -= 1
else:
    print "You lose."


#2

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

    else:
        prompt = "Guess again! "
        guesses_left -= 1

#3

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


#4

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