Jill and Jill
Jill and Jill

Reputation: 39

Conditional statement in while loop not executing everything under it

Basically I'm trying to create a sort of quiz using lists. The code goes like this:

foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",
             "intermediate cuneiform", "medial cuneiform"]
d = len(foot_bones)
def foot_bones_quiz():
    correct_answers = 0
    answers_left = len(foot_bones)
    guess = input("Enter a bone or q to quit: ")
    while True:        
        if guess.lower() == "q":
            break
        elif guess.lower() in foot_bones:
            print("We got a match on index ",foot_bones.index(guess.lower()))
            #Removes the previous guess from the list to ensure the user can't answer the same thing again
            foot_bones.remove(guess.lower())
            guess = ("Enter a bone or q to quit: ")
            correct_answers += 1
            answers_left -= 1
        else:
            answers_left -= 1
            guess = input("No match. Please try again. You have %s tries left. Enter q to quit"%answers_left)

        if answers_left == 0:
            break
    print("You have %s correct answers out of %s."%(correct_answers,d)

foot_bones_quiz()

When I enter "calcaneus", I expected the code to execute everything under the elif statement. What ends up happening is after it prints "We got a match on index blah", the "No match" thing prints which is under the else statement.

What's wrong with my code?

Upvotes: 1

Views: 33

Answers (1)

Primusa
Primusa

Reputation: 13498

I think the guess under your elif should be:

guess = input("Enter a bone or q to quit: ")

Instead of:

guess = ("Enter a bone or q to quit: ")

What's going on is you've entered your first bone which causes your code to get here:

        print("We got a match on index ",foot_bones.index(guess.lower()))
        #Removes the previous guess from the list to ensure the user can't answer the same thing again
        foot_bones.remove(guess.lower())
        guess = ("Enter a bone or q to quit: ")
        correct_answers += 1
        answers_left -= 1

This block executes. Note that guess is set to the value "enter a bone or q to quit: ". You aren't asking for an input.

So now that guess is "enter a bone or q to quit: ", we reach the end of what's under the loop and restart it.

Since guess.lower() isn't in foot_bones and it's not "q" either, you end up in the else statement.

Upvotes: 1

Related Questions