【发布时间】:2012-05-10 07:41:29
【问题描述】:
我是 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)
【问题讨论】:
-
我认为你需要在这里尝试OOP approach。
-
只是好奇...你是 javascript 程序员吗?
-
感谢您的参考,@DrTyrsa。
-
@parselmouth,是的,我是从 javascript 开始的——为什么?
-
@user1186742 您的课程 1() 函数有点像用于生成新对象的 javascript 工厂函数。我想我会问你的 javascript 经验,因为知道你来自 javascript 背景,我们这些同时了解 javascript 和 python 的人可以更好地向你展示 python 如何以不同的方式做某些事情以及为什么。无论如何 - 欢迎来到 python 社区! Python 是一门了不起的语言,我希望您会发现自己喜欢使用它并且使用它非常高效。
标签: python function dictionary arguments