Python · Types: int, float, bool, None
Python's basic scalar types, why 0.1 + 0.2 is not exactly 0.3, and how None differs from False.
Today’s topic was Python’s four basic scalar types.
- int: whole numbers. Python ints have arbitrary precision, so
2**100just works and never overflows. - float: double-precision floating point. Floats are binary approximations, so
0.1 + 0.2is not exactly0.3. Usemath.iscloseto compare them. - bool:
TrueandFalse.boolis a subclass ofint, soTrue + True == 2. - None: the single value of type
NoneType. It means “no value”, and you test for it withis None.
/ always returns a float. // is floor division and % is the remainder. type() tells you what you have.
Truthiness: 0, 0.0, "", [], {} and None are all falsy. Most other values are truthy.
import math
print(2 ** 100)
print(7 / 2, 7 // 2, 7 % 2)
print(0.1 + 0.2, 0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))
print(True + True, isinstance(True, int))
result = None
print(result is None, type(result).__name__)
for v in [0, 1, "", "hi", [], None]:
print(repr(v), "->", bool(v))
Output:
1267650600228229401496703205376
3.5 3 1
0.30000000000000004 False True
2 True
True NoneType
0 -> False
1 -> True
'' -> False
'hi' -> True
[] -> False
None -> FalseSources
- Built-in Types: numeric types — Python Software Foundation
- Floating-Point Arithmetic: Issues and Limitations — Python Software Foundation
- Truth Value Testing — Python Software Foundation