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.

Summary

This lesson demonstrates a Python exercise that teaches looping concepts by repeatedly asking questions to the user. Students create a loop that displays a counter (e.g., "Question 1 out of 4 questions") and iterate through a predefined number of questions. The instructor provides a complete walkthrough using a for loop with range() and string formatting to build a basic question counter system.

Key points

  • Use a for loop with `range()` to iterate through a set number of questions
  • Implement string formatting using the `%` operator to display dynamic question counters (e.g., 'Question %s / %s')
  • Create constants to store configuration values like the total number of questions
  • Use proper indentation within loop blocks for Python code structure
  • Apply arithmetic operations and variable manipulation within loops to track question progress

FAQ

How do you create a loop that displays question counters in Python?

Use a for loop with `range()` to iterate: `for i in range(number_questions):` then use string formatting to display the counter and total, such as `print('Question %s / %s' % (i, number_questions))`.

Why do we use a constant for the number of questions?

Using a constant (like `number_questions = 100`) makes the code more maintainable and allows you to easily change the total number of questions in one place rather than hardcoding it throughout the program.

What is the purpose of this exercise?

This exercise teaches fundamental looping concepts and how to display dynamic feedback to users within loops, preparing students for more complex iterative programming tasks.