Python 6.7 : Addition or multiplication
Right now our math game only asks additions. We want to make it richer by sometimes asking a multiplication instead. The plan is to draw a new random value o for the operator: when o equals 0 the question is an addition, when it equals 1 the question is a multiplication. This way every question randomly picks one of the two operations.
Initialising default values
Inside the function we first initialise an operator variable to the string "+" and a local calculation variable to a + b. Then we check the value of o: if it equals 1, we overwrite both variables to switch to multiplication. The trick of giving defaults up front and overriding them when needed is shorter than chaining if/elif and easier to extend later if we add more operators.
o = random.randint(0, 1)
operator = "+"
calculation = a + b
if o == 1:
operator = "*"
calculation = a * b
answer_int = int(input("Calculate %s %s %s = " % (a, operator, b)))
if answer_int == calculation:
...
Running the program several times now mixes the two kinds of questions: 7 * 7 = 49, 8 + 11, 8 * 2 = 16, 10 + 8, and so on. The score system and the final message still work because we changed nothing else. In the next section we will move on to more advanced concepts around Python functions.
Summary
This lesson teaches how to control whether a Python program performs addition or multiplication by introducing an "operator" variable. The variable holds a value of 0 for addition or 1 for multiplication, allowing the code to dynamically choose between operations. By initializing this variable, the program becomes more flexible and adaptable for future modifications.
Key points
- Introduce an 'operator' variable to control program behavior: 0 triggers addition, 1 triggers multiplication
- Use conditional statements (if/elif) to test the operator value and execute the corresponding operation
- Initializing the operator variable with a default value makes the code more adaptable and easier to modify later
- Examples: 7 × 7 = 49 (multiplication), 8 + 2 = 10 (addition), 8 × 2 = 16 (multiplication)
- This pattern demonstrates how variables can change program logic without rewriting the core code
- Parameterizing operations via variables is a foundational technique for writing flexible and reusable programs
FAQ
How do we decide whether the program adds or multiplies two numbers?
By setting an 'operator' variable: use 0 for addition or 1 for multiplication. The program checks this variable and executes the corresponding operation.
Why is it better to use an operator variable instead of separate code blocks?
Using a variable makes the code flexible and easy to adapt. Instead of rewriting logic, you only change the operator value, keeping the program cleaner and more maintainable.
What values did the lesson demonstrate?
The lesson showed: 7 × 7 = 49, 8 + 2 = 10, and 8 × 2 = 16, confirming that both addition and multiplication operations work correctly based on the operator variable.