Doing math with code: +, -, *, and //
Computers are fast, tireless calculators. Give Python some numbers and a symbol like + or *, and it works out the answer every time the program runs.
The big idea
Python does math with operators: + adds, - takes away, * multiplies, and // divides and keeps only the whole part.
See it in code
The star * means "times." Put it between two variables and Python multiplies what they hold:
trays = 3
cookies_per_tray = 12
baked_today = trays * cookies_per_tray
print("Baked today:", baked_today)Baked today: 36
The answer is stored in a new variable, baked_today, so the rest of the program can use it.
Two slashes, //, divide and keep only the whole part. That's just right for boxes, because half a box can't be sold:
cookies_sold = 20
cookie_price = 3
box_size = 6
money_made = cookies_sold * cookie_price
full_boxes = cookies_sold // box_size
print("Money made: $", money_made)
print("Full boxes:", full_boxes)Money made: $ 60 Full boxes: 3
Twenty cookies fill three boxes of six, with two cookies left over. // drops the leftovers and keeps the 3.
Math places things, too. This fish's tail and eye are measured from the fish's own spot, using minus for behind and plus for in front:
fish_x = 220
fish_y = 200
tail_gap = 70
eye_gap = 40
paper("deep sky blue")
oval(x=fish_x - tail_gap, y=fish_y, width=60, height=80, color="dark orange")
oval(x=fish_x, y=fish_y, width=150, height=90, color="orange")
circle(x=fish_x + eye_gap, y=fish_y - 10, size=16, color="white")
ring(x=320, y=120, size=20, color="white")
ring(x=340, y=80, size=12, color="white")
The tail sits at fish_x - tail_gap, a little to the left of the body. The eye sits at fish_x + eye_gap, a little to the right. Move fish_x and every part follows.
The same four symbols run anything with a number in it. A total on a receipt. The spot of a shape. The speed of a ball. The points in a game.
Try it yourself
Change fish_x = 220 to fish_x = 120 and run it. The whole fish swims left, tail and all. Then make tail_gap bigger. What happens to the tail?
The common mistake
Expecting / and // to be the same. One slash gives a decimal: 20 / 6 is 3.3333333333333335. Two slashes give a whole number: 20 // 6 is 3. Use // when you're counting whole things.
What it unlocks
Math gets more useful once you compare the answers, and it becomes powerful inside a loop, where a running total adds up a whole day of sales.