What You Will Learn
Beginner
- Integer and float operations
- All arithmetic operators
- The math module and common functions
Arithmetic Operators
| Operator | Operation | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 5 - 3 | 2 |
* | Multiplication | 5 * 3 | 15 |
/ | Division | 7 / 2 | 3.5 |
// | Floor division | 7 // 2 | 3 |
% | Modulo (remainder) | 7 % 2 | 1 |
** | Exponent | 2 ** 3 | 8 |
Terminalpython
# Division always returns float in Python 3
print(10 / 2) # 5.0 (float, not int)
print(10 // 3) # 3 (floor division)
print(10 % 3) # 1 (remainder)
print(2 ** 10) # 1024 (2 to the power 10)
# Augmented assignment
x = 10
x += 5 # x = x + 5 = 15
x *= 2 # x = x * 2 = 30
print(x) # 30The math Module
Terminalpython
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.ceil(3.2)) # 4 (round up)
print(math.floor(3.8)) # 3 (round down)
print(math.pow(2, 10)) # 1024.0
print(abs(-5)) # 5
print(round(3.14159, 2)) # 3.14Integer division gotcha
10 / 3 = 3.333 (float). 10 // 3 = 3 (int, truncated). For rounding use round(): round(10/3, 2) = 3.33.Practical Exercise
Calculate: 15 * 3 + 7
Calculate: 2 ** 8 (what is 2 to the 8th power?)
Find remainder: 17 % 5
Use math.sqrt(144) to find square root
Round 3.14159 to 2 decimal places: round(3.14159, 2)
Key Takeaways
- 7 operators: + - * / // % **
- / always returns float. // returns int (floor).
- ** is exponent: 2**10 = 1024.
- % gives remainder: 7 % 2 = 1.
- math module: sqrt, pi, ceil, floor, pow.
- Augmented: x += 5 is x = x + 5.
Comments
Comments
Post a Comment