- Create list of
questions
and its answers
. Save this details in any variable e.g. list.
- Use
for loop
to iterate list items of question and use raw_input()
to ask questions.
- Check User Answer with correct or not by
if condition
.
- If User Answer is wrong, then ask same question to User again.
- If User Answer is correct, then ask next question.
- Use
break
statement to come out from the while loop.
Limitation:
If User not give correct answer to any question then programme will ask same question again and again until User give correct answer.
Demo:
#- 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"
output:
infogrid@infogrid-vivek:~/workspace/vtestproject$
infogrid@infogrid-vivek:~/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.
Multiple choice equations and answers.
Demo:
#- 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
Output:
----------
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