Search code examples
pythonif-statementinline

Not sure why my code keeps printing 'wrong answer'


In my code below, when I input the correct answer, the 'wrong...guess again' keeps printing. This is within the first if statement. I dont know how to set up a conditional for it to print only when the answer is wrong. thanks for the help.

out_of_guesses = False
answer = 'dog'
max_guess = 3
guess = ''
guess_counter = 0

while guess != answer and not(out_of_guesses):
    if guess_counter < max_guess:
       guess = input('pick an animal')
       guess_counter += 1
       print ('wrong...guess again')

    else:
        out_of_guesses = True

if out_of_guesses:
    print ('you lose')
else:
    print('you win')

I typed up everything on the first paragraph.


Solution

  • You put the statement to print in the same if block as the input, meaning it runs with every input. You want to place the "wrong" logic outside of the input logic, or you can add a nested if statement to check what the user input. This code functions how you wish:

    out_of_guesses = False
    answer = 'dog'
    max_guess = 3
    guess = ''
    guess_counter = 0
    
    while guess != answer and not(out_of_guesses):
        if guess_counter < max_guess:
           guess = input('pick an animal')
           guess_counter += 1
        if guess != answer and guess_counter >= max_guess:
            print ('you lose')
            out_of_guesses = True
        elif guess != answer:
            print ('wrong...guess again')
        else:
            print("you win!")