Please enable JavaScript to use CodeHS

Python Tutorial

Basic Math in Python

Python handles math just like you would by hand or with a calculator. Learn the arithmetic operators, PEMDAS, and the surprisingly useful remainder operator.

python ~20 min Beginner friendly
The Big Idea

Math is everywhere

Being able to work with numbers is an essential skill in Python. In fact, it's almost unavoidable! Whether it's converting cups to tablespoons in a baking program, keeping track of a high score in a video game, or placing graphics on a webpage, math is everywhere.

The nice thing about math in Python is that you write it exactly the way you would by hand or on a calculator. This program does some very simple calculations. Press Run to see the results:

main.py
print(6 + 5)
print(1 + 2 + 3 + 4)
print(12 - 16)
Console
11
10
-4

No surprises: Python is happy with negative answers, long chains of numbers, and everything in between. If you can type it on a calculator, you can print it in Python.

The Toolbox

Meet the operators

These are the math symbols (called operators) you can use in Python. The first four look just like regular math. The last three are Python specials, and we will dig into each one below:

+Addition6 + 5 → 11
-Subtraction12 - 16 → -4
*Multiplication4 * 3 → 12
/Division15 / 4 → 3.75
**Exponent2 ** 3 → 8
//Integer division15 // 4 → 3
%Modulus (remainder)15 % 4 → 3

Watch out: exponents use **, not ^. So "two to the third power" is 2 ** 3, which is 8.

Interactive

Calculator vs Python workbench

Try every operator yourself. Type two numbers, pick an operator, and see the exact Python expression and what it gives back. When you pick // or %, the workbench draws the answer with blocks so you can see the remainder:

Workbench

Python expression print(17 // 5)
Result 3

7 % 2 = 1 odd

Order of Operations

PEMDAS still rules

Remember PEMDAS from math class? The same rules apply in Python. Calculations follow the order of Parentheses, then Exponents, then Multiplication and Division, then Addition and Subtraction.

That means 2 + 3 * 4 is not 20. Python multiplies first. Toggle the parentheses on and off and watch the answer change:

PEMDAS mini-lab


Pro tip: when in doubt, add parentheses. They cost nothing, they run first, and they make your code easier for humans to read too.

Level Up

Math with variables

In programming we often mix numbers with variables that store numbers. The math works exactly the same way. This program converts a temperature the user types in from Fahrenheit to Celsius. As you run it, think about these questions:

  • Why do we need variables in this program? Could you write it without variables?
  • round(celsius) rounds the number stored in celsius to the nearest integer. What would the output look like without it?
main.py
# Asks the user to input a temperature value in Fahrenheit
fahrenheit = int(input("Fahrenheit Temperature: "))

# Formula to convert Fahrenheit to Celsius
celsius = (fahrenheit - 32) * (5/9)

# Rounding the variable celsius to the nearest integer
celsius_rounded = round(celsius)

# Prints the original temperature and the converted one
print(str(fahrenheit) + " degrees Fahrenheit = " + str(celsius_rounded) + " degrees Celsius")
Console (if the user types 72)
Fahrenheit Temperature: 72
72 degrees Fahrenheit = 22 degrees Celsius

Spot the PEMDAS: the parentheses in (fahrenheit - 32) * (5/9) are doing real work. Without them, Python would divide and multiply before subtracting, and the formula would be wrong.


Python Specials

Leftovers: integer division and the modulus

Think back to long division, before you learned decimals: 15 divided by 6 is 2, remainder 3. Python has one operator for each half of that answer:

  • 15 // 6 gives 2, how many whole times 6 fits into 15 (integer division)
  • 15 % 6 gives 3, what's left over (the modulus)

If you are new to programming, the modulus can be a little tricky at first. Look at the program below and see if you can figure out what each variable stores before you press Run:

main.py
first = 15 % 6
second = 15 % 5
third = 15 % 4
fourth = 15 % 3
fifth = 15 % 2

print(first)
print(second)
print(third)
print(fourth)
print(fifth)
Console
3
0
3
0
1

Were you able to figure it out? The modulus divides the two numbers, then keeps the remainder:

  • 15 / 6 = 2 with a remainder of 3
  • 15 / 5 = 3 with a remainder of 0
  • 15 / 4 = 3 with a remainder of 3
  • 15 / 3 = 5 with a remainder of 0
  • 15 / 2 = 7 with a remainder of 1

Where would I ever use this?

The remainder shows up everywhere once you start looking:

  • Even or odd: number % 2 is 0 for even numbers and 1 for odd numbers, since even numbers divide by 2 with nothing left over. (That's exactly what the checker in the workbench above is doing!)
  • Clock math: what time is it 5 hours after 9 o'clock? Not 14 o'clock! (9 + 5) % 12 gives 2, so it's 2 o'clock. Clocks "wrap around", and so does the modulus.
  • Sharing leftovers: 17 cookies split between 5 friends? Each friend gets 17 // 5 = 3 cookies, and 17 % 5 = 2 cookies are left on the plate.
Good to Know

Ints, floats, and the two kinds of division

Python has two kinds of numbers: ints (whole numbers like 7) and floats (numbers with a decimal point like 3.5). Most operators give you an int when you feed them ints. Division is the big exception:

  • / always gives a float, even when the answer is a whole number: 10 / 2 is 5.0, not 5
  • // chops off the decimal part and keeps things whole: 10 // 2 is 5
  • Mix an int with a float anywhere and the answer is a float: 2 + 1.5 is 3.5

Try it in the workbench: set the operator to / and divide 10 by 2. See the .0 in the answer? That little tail tells you Python is giving you a float.


Your Turn

Practice: Mini Muffins

1

The Mini Muffies Bakery

You own a specialty bakery called Mini Muffies that sells cute little mini muffins in decorative containers of 3 muffins for $5. At the end of the day, leftover muffins are bagged up in bags of 5 and sold to a local after-school kids organization for a discounted $2 per bag. Any muffins that don't fill a whole bag are set outside to feed the neighborhood squirrels.

Today you baked 543 mini muffins and sold 160 containers at full price. Write a program that:

  • Calculates and prints how many mini muffins were sold at full price
  • Calculates and prints how many muffins did NOT make it into bags and went to the squirrels
  • Calculates and prints how many bags were made and sold at the discounted price
  • Calculates and prints how much total money was earned by the end of the day
  • Refer to the earlier examples as guides while you build your code
  • Use variables to store your calculations along the way
  • The modulus will help you figure out how many muffins go to the squirrels
  • Figure out the squirrels' share before counting the bags (or use // for the bags directly!)

Test cases to check your work:

  • If 181 containers are sold, 0 muffins go to the kids or the squirrels, and you make $905
  • If 100 containers are sold, 3 muffins go to the squirrels, 48 bags go to the kids, and you make $596


solution.py
# Initialize starting variables
total_muffins = 543
containers_sold = 160

# Muffins sold at full price (3 per container)
muffins_sold = containers_sold * 3
print("Sold at full price: " + str(muffins_sold))

# Muffins left over after container sales
muffins_left = total_muffins - muffins_sold

# The squirrels get whatever won't fill a bag of 5
squirrel_muffins = muffins_left % 5
print("For the squirrels: " + str(squirrel_muffins))

# Whole bags of 5 sold at the discounted price
bags_sold = muffins_left // 5
print("Bags for the kids: " + str(bags_sold))

# Total money earned: $5 per container, $2 per bag
total_money = containers_sold * 5 + bags_sold * 2
print("Total earned: $" + str(total_money))
Console
Sold at full price: 480
For the squirrels: 3
Bags for the kids: 12
Total earned: $824

See the teamwork? 543 - 480 leaves 63 muffins. 63 // 5 makes 12 bags and 63 % 5 leaves 3 for the squirrels. Integer division and the modulus split the leftovers perfectly, every time.


Work Smarter

Can we make it simpler? Math shortcuts

Often we only want a very simple calculation. An adventure game might track how many items the player is carrying, and every time the player picks up or drops an item, that count needs to change by 1.

Instead of writing item_count = item_count + 1 every time, you can just write item_count += 1. Both do the same thing! There is a shortcut like this for every operator. Predict the output, then run it:

main.py
x = 2
y = 3
z = 5

# Perform one calculation on itself
x -= 2 # Same as x = x - 2
y *= 3 # Same as y = y * 3
z /= 2 # Same as z = z / 2

print("x: " + str(x))
print("y: " + str(y))
print("z: " + str(z))

# Same idea, but using variables in the calculation
x = 2
y = 3
z = 4

x -= y # Same as x = x - y
y *= z # Same as y = y * z

print("")
print("x: " + str(x))
print("y: " + str(y))
Console
x: 0
y: 9
z: 2.5

x: -1
y: 12

Spot the float: notice that z printed as 2.5. That's the /= shortcut doing real division, which always produces a float.


Code

A math example

Python can do all the basic math operations. This program calculates the perimeter and area of a rectangle.


Check Yourself

Quick quiz

1. What does print(2 + 3 * 4) output?

2. What is 17 % 5?

3. What does print(10 / 2) output?

Keep learning Python

You've got the arithmetic down. Next, unlock square roots, rounding, and more with Python's math module, or use your new operators to generate random numbers for games.