Python - In a function, write a program that creates a dictionary containing the
ID: 3811005 • Letter: P
Question
Python -
In a function, write a program that creates a dictionary containing the U.S. states as keys and their capitals as values. (Use the internet to get a list of the states and thier capitals.) The program should then randomly quiz the user by displaying the name of the state and asking the user to enter the state's capital. THe program should keep a count of the number of correct and incorrect responses.
(As an alternative to the U.S. states, the program can use the names of countries and their capitals.)
Explanation / Answer
import unicodecsv
capitals = {}
with open('us_capital.csv','rb') as f: # Reading csv file into dictionary
reader = unicodecsv.DictReader(f)
for k in reader:
capitals[k['State']] = k['Capital'] #Assigning 1st column of csv as key and 2nd column as value.
right = 0
wrong = 0
for key in capitals.keys():
state = input('Enter the capital of '+key+' :')
if state.upper() == capitals[key].upper():
right += 1
print('Correct')
else:
wrong += 1
print('Incorrect')
choice = input('Do you want to play again y/n: ')
if choice.upper() == 'N':
print('end of game')
break
else:
choice.upper() != 'Y'
print("invalid choice")
break
print('Number of right answers is: ', right) # Print right answers.
print("Number of wrong answers is:", wrong) #Print wrong answers.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.