我是 python 新手,我正在构建一个游戏来自学 python。这场比赛将有许多课程,有问题和答案;用户将根据其答案的有效性获得和失去积分。
我正在使用字典来存储将在每节课中提出的问题和答案。
我只想在特定点(例如,在用户输入命令后)显示和检查字典的键和值。为此,我想我可以创建包含字典的函数,然后在需要时将它们传递给主函数。
但是当我运行下面的代码时,出现以下错误: AttributeError: 'function' object has no attribute 'iteritems'
所以我有两个问题:
- 我尝试从函数中删除字典,然后它工作得很好。有什么方法(或理由)让它在一个函数中工作吗?
- 是否可以只使用一个字典并在某些点检查其中一部分的键和值?
到目前为止,这是我的代码。任何建议将不胜感激!
points = 10 # user begins game with 10 pts
def point_system():
global points
#help user track points
if 5 >= points:
print "Careful. You have %d points left." % points
elif points == 0:
dead("You've lost all your points. Please start over.")
else:
print "Good job. Spend your points wisely."
def lesson1():
#create a dictionary
mydict = {
"q1":"a1",
"q2":"a2"
}
return mydict
def main(lesson):
global points
#get key:value pair from dictionary
for k, v in lesson.iteritems():
lesson.get(k,v) # Is the .get step necessary? It works perfectly well without it.
print k
user_answer = raw_input("What's your answer?: ")
#test if user_answer == value in dictionary, and award points accordingly
if user_answer == v:
user_answer = True
points += 1 #increase points by 1
print "Congrats, you gained a point! You now have %d points" % points
point_system()
elif user_answer != v:
points -= 1 #decrease points by 1
print "Oops, you lost a point. You now have %d points" % points
point_system()
else:
print "Something went wrong."
point_system()
main(lesson1)
和有效的代码:
points = 10 # user begins game with 10 pts
#create a dictionary
lesson1 = {
"q1":"a1",
"q2":"a2"
}
def point_system():
global points
#help user track points
if 5 >= points:
print "Careful. You have %d points left." % points
elif points == 0:
dead("You've lost all your points. Please start over.")
else:
print "Good job. Spend your points wisely."
def main(lesson):
global points
#get key:value pair from dictionary
for k, v in lesson.iteritems():
lesson.get(k,v) # Is the .get step necessary? It works perfectly well without it.
print k
user_answer = raw_input("What's your answer?: ")
#test if user_answer == value in dictionary, and award points accordingly
if user_answer == v:
user_answer = True
points += 1 #increase points by 1
print "Congrats, you gained a point! You now have %d points" % points
point_system()
elif user_answer != v:
points -= 1 #decrease points by 1
print "Oops, you lost a point. You now have %d points" % points
point_system()
else:
print "Something went wrong."
point_system()
main(lesson1)