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
Step: 1
import random Create a dictionary to hold the states and capitals statescapitals Open the StatesC...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started