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

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.

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 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:
            print ('wrong...guess again')
       else:
           print("you win!")

    else:
        out_of_guesses = True

    if out_of_guesses:
        print ('you lose')
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