Numbers and Arithmetic

Python can compute with numbers directly:

Output:

5
3
24
5.0

The last result is 5.0, not 5, because / performs division and returns a floating-point number.

Integers and Floats

Python has different numeric types. The two you will see first are:

TypeExampleMeaning
int7integer
float7.0floating-point number

An int represents whole numbers. A float represents numbers that may contain a decimal part.

Arithmetic Operators

Common arithmetic operators:

OperatorMeaningExample
+addition2 + 3
-subtraction5 - 2
*multiplication4 * 3
/division10 / 4
//floor division10 // 4
%remainder10 % 4
**power2 ** 3

Arithmetic operators

Run the code and compare division, floor division, and remainder.

Runs locally with Python in your browser.

Ready to run.

Order of Operations

Python follows familiar arithmetic precedence:

Output:

14
20

Use parentheses when they make the intention clear. Clear code is better than clever code.

Power Uses Two Asterisks

Do not use ^ for powers:

2 ^ 3

That is not exponentiation in Python. Use:

2 ** 3
Exercise: Compute an expression

What is the value of this expression?

(2 + 3) * 4

Compute it first, then check your number.

HintUse the parentheses first

Compute 2 + 3, then multiply that result by 4.

SolutionThe value is twenty

Parentheses make 2 + 3 happen first, producing 5. Then 5 * 4 produces 20.

Use Arithmetic Deliberately

Numbers are the first values we compute with. Later, NumPy arrays and tensors will hold many numbers at once, but the habits start here: compute, print, and inspect.