What would be the correct way to implement a "Try again" message for a simple guessing game?

I’m trying to implement a text that says "Try again" to appear when the player guesses incorrectly. This is an extremely bare bones "game" but I started coding yesterday and I’m trying to learn all the basic functions and methods. This is the code:

secret_number = 9
guess_limit = 3
guess_count = 0
while guess_count < guess_limit:
    guess = int(input("Guess:"))
    guess_count += 1
    if guess == secret_number:
        print("You won!")
        break
else:
    print("You lost!")

I tried using another "else" function and another "if" function but I couldn’t figure it out.

>Solution :

You can print 'Try again' after checking if the player guesses correctly. To avoid printing 'Try again' in the last guess, use an additional if statement:

secret_number = 9
guess_limit = 3
guess_count = 0
while guess_count < guess_limit:
    guess = int(input("Guess:"))
    guess_count += 1
    if guess == secret_number:
        print("You won!")
        break
    if guess_count < guess_limit: # add these two lines
        print('Try again')
else:
    print("You lost!")

Demo: https://replit.com/@blhsing/RaggedGleamingMenus

Leave a Reply