Question: Write a program that creates a dictionary containing the U.S. states as keys, and their capitals as values. #The program should then randomly quiz the

Write a program that creates a dictionary containing the U.S. states as keys, and their capitals as values.
#The program should then randomly quiz the user (you may limit the number of random quizzes to 5) by displaying the name of a state and asking the
#user to enter that state's capital. The program should keep a count of the number of correct and incorrect responses.
#StatesCapitals.txt is a text file with states, abbreviations, and their capitals

# Create  dictionary to hold the states and capitals
import random


# Create dictionary to hold the states and capitals
states_capitals = {}

# Open the StatesCapitals.txt file and read in the data
with open("StatesCapitals.txt", "r") as file:
for line in file:
    # Split the line into state, abbreviation, and capital
    # If there are not exactly 3 values in the split line, skip the line
    try:
        state, abbrev, capital = line.strip().split(",")
    except ValueError:
        continue
   
    # Add the state and capital to the dictionary
    states_capitals[state] = capital

# Initialize the counters for correct and incorrect responses
correct = 0
incorrect = 0

# Randomly select 5 states to quiz the user on
states_to_quiz = random.sample(list(states_capitals.keys()), len(states_capitals))

# Quiz the user on the state capitals
for state in states_to_quiz:
capital = input("What is the capital of " + state + "? ")
if capital.lower() == states_capitals[state].lower():
    print("Correct!")
    correct += 1
else:
    print("Incorrect. The capital of " + state + " is " + states_capitals[state] + ".")
    incorrect += 1

# Print the results
print("You got " + str(correct) + " out of " + str(len(states_capitals)) + " questions correct.")

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

import random Create a dictionary to hold the states and capitals statescapitals Open the StatesC... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!