Because your pattern seems to involve a question (questionText
) and an answer (answer
), perhaps it would be better to create a function simply for that purpose (question
). This removes code duplication and makes it easier to extend in the future.
In this example I created a function called question
that accepts parameters questionText
and answer
. Then I created a list of questions (composed of a questionText
and an answer
) that I would like to ask, in the order that they should be asked.
Then I use a for
loop to iterate through all questions, assigning questionText
and answer
in each iteration. There is a while
loop inside this for
loop that continues to ask the user for a response. If the response is correct, the question
will return True
, and the while
loop will stop because question(questionText, answer) is True
(which is opposite of the while
loop's condition). Then after a correct response, Correct! Next question!
is printed, and it moves to the next question from the list.
# Defines a 'question' function which accepts:
# questionText - the question to be asked
# answer - the answer to the question
# Returns True if the answer is correct
def question(questionText, answer):
if int(input(questionText + ' ')) == answer:
return True
# Creates a list of questions and their respective answers
questionList = [
('What is the square root of 9?', 3),
('What is 2 plus 2?', 4),
('What is 10 divided by 5?', 2)
]
# Iterates through all questions in the questionList and asks the user each question.
# If the user response equals the answer, outputs 'Correct! Next question!'
# If the user response does not equal the answer, outputs 'Wrong! Think harder!'
for questionText, answer in questionList:
while question(questionText, answer) is not True:
print('Wrong! Think harder!')
print('Correct! Next question!')