私はPythonの初心者です。私は自分自身にPythonを教えるためのゲームを構築しています。このゲームには、質問と回答を含む数多くのレッスンがあります。ユーザーは回答の正当性に応じてポイントを獲得し失うことになります。Python:辞書を含む関数を別の関数に渡すには?
私は各レッスンで質問される質問と回答を辞書で保存しています。
辞書のキーと値を特定のポイント(たとえば、ユーザーがコマンドを入力した後)で表示し、チェックしたいとします。これを行うために、辞書を含む関数を作成し、必要に応じてそれらを主関数に渡すことができると想像しました。
しかし、私は以下のコードを実行すると、私は次のエラーを取得する:はAttributeError:「関数」オブジェクトが無属性「iteritems」
を持っているので、私は2つの質問があります:私は削除しようとした
- を関数内から辞書を検索すると、 が正常に動作します。 内で機能させる方法(または理由)はありますか?
- 辞書を1つだけ使用して、特定のポイントでセクションのキーと値を確認することはできますか?
ここまでは私のコードです。どんなアドバイスも大いにありがとう!
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)
と動作するコード:あなたはlesson1機能ではなく(ディレクトリ)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アプローチ](http://docs.python.org/tutorial/classes.html)を試してみる必要があると思います。 – DrTyrsa
ちょうど興味深い...あなたはJavaScriptのプログラマーですか? – parselmouth
リファレンス、@DrTyrsaありがとうございます。 – user1186742