Module lessons (3/4)
Numbers and the math module
Python distinguishes two fundamental numeric types: int (arbitrary-precision
integers — no overflow) and float (64-bit floating point, double
precision).
type(42) # <class 'int'>
type(3.14) # <class 'float'>
type(10 ** 100) # <class 'int'> — interi grandi a piacereArithmetic operators
| Op | Meaning | Example | Result |
|---|---|---|---|
+ | addition | 2 + 3 | 5 |
- | subtraction | 5 - 2 | 3 |
* | product | 4 * 3 | 12 |
/ | true division | 10 / 4 | 2.5 |
// | integer division | 10 // 4 | 2 |
% | modulo (remainder) | 10 % 3 | 1 |
** | power | 2 ** 10 | 1024 |
Warning: / always returns a float, even with two integers (10 / 2
returns 5.0, not 5). For integer division use //.
10 / 4 # 2.5
10 // 4 # 2
-7 // 2 # -4 (arrotonda verso il basso, non verso lo zero)Numeric built-ins
abs(-5) # 5
min(3, 1, 2) # 1
max([3, 1, 2]) # 3 (su iterabile)
round(3.7) # 4
round(3.14159, 2) # 3.14
sum([1, 2, 3]) # 6The math module
import math
math.pi # 3.141592653589793
math.sqrt(16) # 4.0
math.floor(3.9) # 3 (verso meno infinito)
math.ceil(3.1) # 4 (verso più infinito)
math.log(math.e) # 1.0
math.gcd(12, 18) # 6The float pitfall
Floats are binary approximations: 0.1 + 0.2 does not exactly equal
0.3.
0.1 + 0.2 # 0.30000000000000004
0.1 + 0.2 == 0.3 # False !For safe comparisons use math.isclose(a, b) or, in financial contexts, the
decimal module.
Float precision and the decimal module
Floats in Python are implemented as double-precision floating-point numbers (IEEE 754 standard). Consequently, calculations like 0.1 + 0.2 do not yield exactly 0.3, but rather 0.30000000000000004. If you require absolute mathematical precision (e.g. for financial applications), use the standard library's decimal module.
Try it
Given `seconds = 3725`, compute `hours`, `minutes`, `remaining_seconds` using // and %. Evaluate the tuple `(hours, minutes, remaining_seconds)`.
Show hint
// does integer division, % the remainder.
Solution available after 3 attempts
Review exercise
Given `radius = 5`, compute the circle area in `area` using math.pi. Evaluate `area` rounded to 2 decimals with round.
Show hint
math.pi * radius ** 2
Solution available after 3 attempts
Additional challenge
Import the `math` module. Calculate the square root of `16` using `math.sqrt`, add the result to the rounded value of `3.74` (using `round()`), and store the final sum in `total_val`. Finally, evaluate the variable.
Show hint
math.sqrt(16) returns 4.0. round(3.74) returns 4. Sum them and assign to total_val.
Solution available after 3 attempts