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:
| Type | Example | Meaning |
|---|---|---|
int | 7 | integer |
float | 7.0 | floating-point number |
An int represents whole numbers. A float represents numbers that may contain
a decimal part.
Arithmetic Operators
Common arithmetic operators:
| Operator | Meaning | Example |
|---|---|---|
+ | addition | 2 + 3 |
- | subtraction | 5 - 2 |
* | multiplication | 4 * 3 |
/ | division | 10 / 4 |
// | floor division | 10 // 4 |
% | remainder | 10 % 4 |
** | power | 2 ** 3 |
Arithmetic operators
Run the code and compare division, floor division, and remainder.
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
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.