Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading