Skip to main content

Unit 2 · Python mode... Activate! · Lesson 20 of 57

Math Mania

Math Mania

Python is basically a really fancy calculator. You've already seen + and -. Here's the whole gang:

SymbolWhat it doesExampleAnswer
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23.5
//divide, then chop off the decimal7 // 23
%remainder7 % 21
**power (exponent)7 ** 249

The first four you know from school. The last three need a little more explaining.

The pizza problem

Say we order a pizza with 17 slices. (Weird pizza, I know.) There are 5 of us: me, Amer, Zain, Alex and Rishabh.

17 // 5 is 3. That's how many slices each person gets. // divides, then throws away anything after the decimal point, because you can't really hand someone 0.4 of a slice. (Well, you can, but it's messy.)

17 % 5 is 2. That's how many slices are left over after everyone gets their 3. % gives you the remainder, just like long division back in elementary school. (It's called modulus, if you want to sound smart.)

(The 2 leftover slices go to Amer.)

Powers

** is for exponents. 2 ** 3 means 2 * 2 * 2, which is 8. You'll see this a lot if you ever get into cryptography, so tuck it away!

Order of operations

Python follows the same order of operations you learned in math class (PEMDAS!). Parentheses first, then exponents, then multiplication and division, then addition and subtraction.

print(2 + 3 * 4)    # 14, not 20!
print((2 + 3) * 4)  # 20

See the #? Anything after a # is a comment. Python completely ignores it, so you can leave notes for yourself. (Or for Amer, who clearly needs them.)

Let's split the pizza!

Use slices and people to print two things, each on its own line:

  1. How many slices each person gets
  2. How many slices are left over

Use the variables, not the numbers, so it still works when Alex orders a bigger pizza.

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Do this lesson for real

With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.