- 創建的
questions
及其answers
列表。將這些細節保存在任何變量中名單。
- 使用
for loop
可迭代問題列表項並使用raw_input()
提問。
- 檢查用戶答案是否正確通過
if condition
。
- 如果用戶回答錯誤,則再次向用戶提出同樣的問題。
- 如果用戶回答正確,則詢問下一個問題。使用
break
聲明從while循環中出來。
限制: 如果用戶沒有給出正確回答任何問題,然後程序會一次又一次地問同一個問題,直到用戶給出正確的答案。
演示:
#- Create List of tuples which contains question and respective answer.
questions = [("Question number one?", "one"), ("Question number two?", "two"),\
("Question number three?", "three")]
for i in questions:
while 1:
ans = raw_input(i[0])
if ans==i[1]:
print "Correct."
break
else:
print "Wrong answer"
輸出:
[email protected]:~/workspace/vtestproject$
[email protected]:~/workspace/vtestproject$ python task4.py
Question number one?test1
Wrong answer
Question number one?test1
Wrong answer
Question number one?one
Correct.
Question number two?two
Correct.
Question number three?test3
Wrong answer
Question number three?three
Correct.
選擇題方程和解答。
演示:
#- Create List of tuples which contains question. optinons and respective answer.
questions = [("Question number one?", ["a. one", "b. two", "c. three"], "a"),\
("Question number two?", ["a. one", "b. two", "c. three"], "b"),\
("Question number three?", ["a. one", "b. two", "c. three"], "c")
]
#- Set number of chances to solve each question.
chances = 3
#- Score. Plus one for each correct answer.
score = 0
for i in questions:
print "-"*10
for j in xrange(0, chances):
print "Question:", i[0], "\n Options:", i[1]
ans = raw_input("Enter option:")
if ans==i[2]:
print "Correct."
score += 1
break
else:
print "Wrong answer"
print "Your score: ", score
輸出:
----------
Question: Question number one?
Options: ['a. one', 'b. two', 'c. three']
Enter option:b
Wrong answer
Question: Question number one?
Options: ['a. one', 'b. two', 'c. three']
Enter option:c
Wrong answer
Question: Question number one?
Options: ['a. one', 'b. two', 'c. three']
Enter option:b
Wrong answer
----------
Question: Question number two?
Options: ['a. one', 'b. two', 'c. three']
Enter option:b
Correct.
----------
Question: Question number three?
Options: ['a. one', 'b. two', 'c. three']
Enter option:s
Wrong answer
Question: Question number three?
Options: ['a. one', 'b. two', 'c. three']
Enter option:c
Correct.
Your score: 2
看起來你需要使用多個循環。我會爲每個問題使用一個循環,當您想要移動到下一個問題時使用「break」。 – Sam 2015-03-02 08:13:45