Python 6.4 : Exercise : Several questions

In the previous video our function only asked a single math question. Now we want the game to ask several questions in a row. To get there, we first declare a constant NUMBER_OF_QUESTIONS = 5 at the top of the file, then write a loop that displays "Question 1 of 5", "Question 2 of 5", and so on, calling our question function each time. Try it on your own first, then have a look at the correction.

Looping with for and range

For the correction we use a for loop combined with range. The lower bound is the inclusive value 0 and the upper bound is the exclusive constant NUMBER_OF_QUESTIONS. Inside the loop we build a small header with "Question %s of %s" using i + 1 (because i starts at zero) and the total number of questions, then we call our existing function.

NUMBER_OF_QUESTIONS = 5

for i in range(0, NUMBER_OF_QUESTIONS):
    print("Question %s of %s:" % (i + 1, NUMBER_OF_QUESTIONS))
    question()

Running the program now shows "Question 1 of 5", asks for example to compute 10 + 2, prints "correct answer" when we reply 12, and immediately moves on to question 2 and so forth. We can already play five rounds in a row. In the next video we will start counting the number of points and turn this loop into a real scored game.