我不明白为什么我的程序没有随机选择键值对。每次运行该程序时,总是会要求我选择相同州(蒙大拿州,夏威夷,马萨诸塞州,华盛顿州和明尼苏达州)的首府,即使有8个键可供选择。
尽管IDLE没有报告任何错误,但我认为程序中存在错误。请帮助我识别它。下面是我的程序:
#Define main function
def main ():
#Create a dictionary that contains the state and its capital
state_dictionary = {"New York": "Albany", "New Jersey": "Trenton",
"California": "Sacramento", "Minnesota": "Saint Paul",
"Washington": "Olympia", "Massachusetts": "Boston",
"Hawaii": "Honolulu",
"Montana": "Helena"}
#Initialize an accumulator for the number of correct answers
correct = 0
#Initialize an accumulator for the number of incorrect answers
incorrect = 0
#Iterate over the dictionary
#This loop will repeat 5 times
for y in range (5):
#Return a randomly selected key-value pair with the key being
#the variable "state" and the value being the variable "capital"
state, capital = state_dictionary.popitem()
#Ask the user for the capital of the randomly selected state
x = input ("What is the capital of " + state + "?")
#If uppercase version of user's input is equal to uppercase
#version of correct answer to the question, add 1 to total number of
#correct answers
if x.upper() == capital.upper():
correct += 1
#If any other response is entered, add 1 to total number of
#incorrect answers
else:
incorrect += 1
#Display the number of correct and incorrect answers
print ("You got", correct, "correct answers, and", incorrect,
"incorrect answers.")
#Call main function
main ()
根据dict.popitem()
功能的文档:
从字典中删除并返回(键,值)对。配对按LIFO顺序返回。
dict.popitem()
可用于破坏性地迭代字典,这在集合算法中经常使用。如果字典为空,则调用popitem()
会引发KeyError。在3.7版中更改:现在可以保证LIFO顺序。在以前的版本中,popitem()将返回任意键/值对。
解决此问题的一种可能方法是使用popitem()
:
random