DarthOpto
DarthOpto

Reputation: 1652

Do Not Display Message While in IF statement

I am going through "Python Programming for the absolute beginner - Third Edition" and inside of that there is a word jumble game. One of the exercises is to offer a hint to the user when they have guessed incorrectly. I have it working however when the hint statement is executed it also prints out the incorrect guess message, and I am stumped as to how to make it not print the incorrect guess message while in the hint.

Here is the code:

guess = input("\nYour guess: ")
wrong_guess_msg = "Sorry that was not correct. Try again."
while guess != correct and guess != "":
    print(wrong_guess_msg)
    guess = input("Your guess: ")
    guess_count += 1
    # Ask the user if they would like a hint after 4 wrong guesses
    if guess_count == 4:
        hint_response = input("Would you like a hint?: ")
        if hint_response.lower() == "yes":
            print("Here is your hint: {}".format(hint))
    else:
        guess = input("Your guess: ")

I have tried pulling the if guess_count statement out of the while loop, however it never executes. I tried change the while loop to include a condition where the guess_count != 4 and that sort of worked, meaning I didn't get the incorrect guess when I got the hint, however it exited the program.

Just not really sure what I am missing here.

Upvotes: 1

Views: 66

Answers (1)

Thomas Lotze
Thomas Lotze

Reputation: 5313

You could structure the whole loop differently, thereby also eliminating the first prompt before the start of the loop:

wrong_guess_msg = '...'
while True:
    guess = input('Your guess: ')
    guess_count += 1
    if guess == correct:
        break
    if guess_count == 4:
        ...

You may argue that this is leaving the while condition unused, but by that, you gain the chance to write your code straight and clean, exactly because you're not forced to put the correctness check right in front of each iteration. Always (if possible) let yourself be guided by how you would spell out an algorithm if explaining it to the next person, rather than by loop mechanics or other technical constraints.

Upvotes: 2

Related Questions