Skip to main content
eLearner.app
Module 4 · Lesson 3 of 415/36 in the course~10 min
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).

Python
type(42)       # <class 'int'>
type(3.14)     # <class 'float'>
type(10 ** 100)  # <class 'int'>   — interi grandi a piacere

Arithmetic operators

OpMeaningExampleResult
+addition2 + 35
-subtraction5 - 23
*product4 * 312
/true division10 / 42.5
//integer division10 // 42
%modulo (remainder)10 % 31
**power2 ** 101024

Warning: / always returns a float, even with two integers (10 / 2 returns 5.0, not 5). For integer division use //.

Python
10 / 4    # 2.5
10 // 4   # 2
-7 // 2   # -4   (arrotonda verso il basso, non verso lo zero)

Numeric built-ins

Python
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])        # 6

The math module

Python
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)      # 6

The float pitfall

Floats are binary approximations: 0.1 + 0.2 does not exactly equal 0.3.

Python
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

Exercise#python.m4.l3.e1
Attempts: 0Loading…

Given `seconds = 3725`, compute `hours`, `minutes`, `remaining_seconds` using // and %. Evaluate the tuple `(hours, minutes, remaining_seconds)`.

Loading editor…
Show hint

// does integer division, % the remainder.

Solution available after 3 attempts

Review exercise

Exercise#python.m4.l3.e2
Attempts: 0Loading…

Given `radius = 5`, compute the circle area in `area` using math.pi. Evaluate `area` rounded to 2 decimals with round.

Loading editor…
Show hint

math.pi * radius ** 2

Solution available after 3 attempts

Additional challenge

Exercise#python.m4.l3.e3
Attempts: 0Loading…

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.

Loading editor…
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