Python 6.3 : Exercise : Addition

Now we want our math game to actually ask a question. The idea is to write a function called question that picks two numbers a and b at random, asks the user to compute a + b and tells them whether the answer is correct or not. Try writing it on your own first, then compare with the version below.

Building the question function

Inside the function we call random.randint(MIN, MAX) twice to get the two operands. We use the %s placeholders to build the prompt that asks the user to calculate a + b, then read their answer through input. Because input returns a string, we convert it to an integer before comparing it to the real sum.

def question():
    a = random.randint(MIN, MAX)
    b = random.randint(MIN, MAX)
    answer_str = input("Calculate %s + %s = " % (a, b))
    answer_int = int(answer_str)
    if answer_int == a + b:
        print("Correct answer")
    else:
        print("Incorrect answer")

question()

When we run the program it draws two numbers, asks the operation and reads our reply. Typing the right total prints "correct answer"; typing anything else prints "incorrect answer". The function is short, focused and easy to reuse. In the next video we will call it several times in a loop so the game actually asks more than a single question per session.

Summary

This lesson teaches how to build an interactive Python addition exercise program that asks users to solve arithmetic problems. The program generates random numbers, prompts users for answers, validates their responses, and provides immediate feedback on correctness. It demonstrates a practical application of user input handling, random number generation, and conditional logic wrapped in a loop for multiple practice questions.

Key points

  • Using the input() function to accept and process user responses
  • Generating random numbers to create dynamic addition problems
  • Comparing user answers against the correct calculation (a + b)
  • Providing immediate feedback on whether answers are correct or incorrect
  • Implementing a loop structure to deliver multiple sequential questions without program restart

FAQ

How does the program generate the numbers for each addition problem?

The program uses random number generation to create two numbers (a and b) for each question.

How does the program check if the user's answer is correct?

The program calculates the correct sum (a + b) and compares it to the user's provided response to determine correctness.

Can users answer multiple questions in one session?

Yes, the lesson demonstrates using a loop structure to ask multiple addition questions sequentially without restarting the program.