CodeStride
Getting Started

Numbers and math in Python

Topic 3 of 58 · 9 minFree lesson

Python is a very good calculator. It handles two kinds of numbers:

  • An integer (or int) is a whole number, like 7, -3 or 2026.
  • A float is a number with a decimal point, like 3.5 or 0.25.

The math signs

These signs are called operators. Most of them look like the ones you know.

Example 1
print(10 + 4)print(10 - 4)print(10 * 4)print(10 / 4)
146402.5

* means multiply and / means divide. Division always gives a float, even when the answer is whole.

Example 2
print(8 / 2)
4.0

Whole division and remainders

Say you share 17 cookies between 5 friends. Each friend gets 3, and 2 are left over. Python has a sign for each part.

Example 3
print(17 // 5)print(17 % 5)
32

// divides and drops the part after the decimal point. % gives the remainder: what's left over. A handy use: a number is even when number % 2 is 0.

Powers

** raises a number to a power. 2 ** 3 means 2 times 2 times 2.

Example 4
print(2 ** 3)
8

Order of operations

Python follows the same order as math class. It multiplies and divides before it adds and subtracts. Use brackets to choose the order yourself.

Example 5
print(2 + 3 * 4)print((2 + 3) * 4)
1420

Updating a number

Often you want to change a number using its old value, like adding points to a score.

Example 6
score = 10score = score + 5print(score)
15

The shortcut += does the same thing in less space. There's also -=, *= and /=.

Example 7
score = 10score += 5print(score)
15
NoteFloats can be slightly off in the last digit. This is normal for computers, not a bug in your code. Use round() to tidy them up.
Example 8
print(0.1 + 0.2)print(round(0.1 + 0.2, 2))
0.300000000000000040.3
Common mistakeWriting big numbers with commas, like 1,000. Python reads the comma as a separator and sees two numbers, 1 and 000.
Example 9
print(1,000)
1 0

Write 1000 instead. If you want a separator, use an underscore: 1_000 is the same number.

Try it yourself

Run the code in the editor and answer 8 practice questions on numbers and math. It's free, you only need an account.