Search code examples
pythondictionaryinputoutputkey-value-store

Capital Quiz Using Dictionary Values In A For Loop


I am required to create a quiz that uses 5 states and capitals and requests the user to answer the matching capital. I cannot figure out how to print the individual value or individual key in order to generate the question. As my code is right now, it prints out every value in the dictionary.

I have tried various methods including index locations but they only resulted in error messages. I assume that index locations are not available when using a dictionary in Python.

states = {'Colorado':'Denver', 'Ohio':'Columbus', 
'Florida':'Tallahassee','Arizona':'Phoenix', 'Mississippi':'Jackson' }

for values in states:
    state = states.keys()
    capital = states.values()
    print('What is the capital of:', state)
    answer = input("Please type your answer: ")
    if (answer == capital):
        print("\n", "You have guessed correctly!")
        correct += 1
    else:
        print("\n", "Sorry the answer is", capital)
        incorrect += 1

I expect the printed state to be an individual state with each one being printed in succession. Then the user is prompted for the capital. If the capital matches it should gather it as a correct answer, otherwise it should print out the correct capital and the incorrect error message.


Solution

  • try

    states = {'Colorado':'Denver', 'Ohio':'Columbus',
    'Florida':'Tallahassee','Arizona':'Phoenix', 'Mississippi':'Jackson' }
    correct = 0;
    incorrect = 0
    for state in states:
        capital = states[state]
        print("\nWhat is the capital of:", state)
        answer = input("Please type your answer: ")
        if (answer == capital):
            print("You have guessed correctly!")
            correct += 1
        else:
            print("Sorry the answer is", capital)
            incorrect += 1
    print("got",correct,"correct and",incorrect,"incorrect answer" )