Numbers and math in Python
Topic 3 of 58 · 9 minFree lessonPython is a very good calculator. It handles two kinds of numbers:
- An integer (or int) is a whole number, like
7,-3or2026. - A float is a number with a decimal point, like
3.5or0.25.
The math signs
These signs are called operators. Most of them look like the ones you know.
print(10 + 4)print(10 - 4)print(10 * 4)print(10 / 4)* means multiply and / means divide. Division always gives a float, even when the answer is whole.
print(8 / 2)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.
print(17 // 5)print(17 % 5)// 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.
print(2 ** 3)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.
print(2 + 3 * 4)print((2 + 3) * 4)Updating a number
Often you want to change a number using its old value, like adding points to a score.
score = 10score = score + 5print(score)The shortcut += does the same thing in less space. There's also -=, *= and /=.
score = 10score += 5print(score)round() to tidy them up.print(0.1 + 0.2)print(round(0.1 + 0.2, 2))1,000. Python reads the comma as a separator and sees two numbers, 1 and 000.print(1,000)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.