既然你剛開始學習Python的,我重新格式化你的代碼更Python。
def q(question, a, b, c, c_answer):
total, tally = 0, 0
print "", question
print " a. %s" % a
print " b. %s" % b
print " c. %s" % c
u_answer = raw_input("your answer? ").strip()
if c_answer == u_answer:
print "Correct, the answer is %s!" % u_answer
tally += 1
else:
print "I am sorry, but the correct answer is %s" % c_answer
print "\n"
total += 1
要真正回答你的問題:
有幾種方法可以跟蹤的問題和正確答案總數不使用全局級變量(實際上是模塊級,但是這一個不同的話題;)。
一個是在當前總計通過,已根據當前問題q
重新計算,然後將它們傳回了:
def q(question, a, b, c, c_answer, total, tally):
print "", question
print " a. %s" % a
print " b. %s" % b
print " c. %s" % c
u_answer = raw_input("your answer? ").strip()
if c_answer == u_answer:
print "Correct, the answer is %s!" % u_answer
tally += 1
else:
print "I am sorry, but the correct answer is %s" % c_answer
print "\n"
total += 1
return total, tally
然後在你的主要程序,你可以說:
question_pool = (
('What is 2 + 2?', 2, 3, 4, 'c'),
('What is blue mixed with yellow?', 'green', 'orange', 'pink', 'a'),
('How far does light travel in one nanosecond?', '10 mm', '20 cm', '30 m', 'b'),
)
total, tally = 0, 0
for packet in question_pool:
question, a, b, c, answer = packet
total, tally = q(question, a, b, c, answer, total, tally)
print "you answered %d correctly, for a score of %2.0f%%" % (tally, 100.0 * tally/total)
但是,q
只處理問題會更好,不用擔心跟蹤回答了多少個問題紅色以及問了多少問題。的
所以不是接受total
和tally
,重新計算,並返回total
和tally
,q
現在只返回0
如果答案是錯的,1
如果這是正確的:
def q(question, a, b, c, c_answer):
print "", question
print " a. %s" % a
print " b. %s" % b
print " c. %s" % c
u_answer = raw_input("your answer? ").strip()
if c_answer == u_answer:
print "Correct, the answer is %s!\n" % u_answer
return 1
print "I am sorry, but the correct answer is %s" % c_answer
return 0
和的休息代碼看起來像:
question_pool = (
('What is 2 + 2?', 2, 3, 4, 'c'),
('What is blue mixed with yellow?', 'green', 'orange', 'pink', 'a'),
('How far does light travel in one nanosecond?', '10 mm', '20 cm', '30 m', 'b'),
)
total, tally = 0, 0
for packet in question_pool:
question, a, b, c, answer = packet
tally += q(question, a, b, c, answer)
total += 1
print "you answered %d correctly, for a score of %.0f%%" % (tally, 100.0 * tally/total)
哪個版本ru使用? – Teja 2012-03-05 19:11:32
我正在使用版本2.7 – 2012-03-05 19:13:28
定義「平均功能」。 – delnan 2012-03-05 19:13:43