Operators: do math in your code
Code can do math for you. With +, -, and *, your program adds up a hero's power, doubles a score, or works out anything you need.
The big idea
An operator like + or * takes two numbers and gives you a new one.
See it in code
Code can do math for you. The + operator takes two numbers and gives back a new one:
hearts = 2 + 1
print(hearts)3
2 + 1 became 3, and we stored it in hearts. An operator's job is to turn numbers into a new number.
The * operator means multiply — computers use * instead of a × sign. Here it doubles a number:
coins = 5
doubled = coins * 2
print(doubled)10
5 * 2 made 10. Swap the 2 for a bigger number to triple or quadruple instead.
Our hero has some strength and some magic. Total power is just the two added together. We use + to add, then * to double it for a boost:
strength = 12
magic = 8
power = strength + magic
print("Total power:", power)
boost = power * 2
print("With a boost:", boost)Total power: 20 With a boost: 40
12 + 8 made 20, and 20 * 2 made 40. The * means multiply — computers use * instead of the × sign.
Math operators run under the hood of everything. A game adds points, art multiplies a position to space stars out, a money app subtracts a cost. Once you can add and multiply in code, you can compute anything.
Try it yourself
Give the hero armor: make a box armor = 5 and add it to power. Then try - to spend 10 power on a spell, and print what is left.
The common mistake
Using x for times. In code, 2 x 3 is an error — the multiply sign is the star *. Write 2 * 3 to get 6.
What it unlocks
Numbers you compute get compared with comparison operators and stored in variables to use again later.