The types you will use every day
type(x) tells you what something is; isinstance(x, int) asks whether it counts as one. Prefer isinstance — it respects subclasses, which is why isinstance(True, int) is True.
| Type | Example | Note |
|---|---|---|
int | 42, -7, 10**100 | Unbounded. There is no overflow and no long |
float | 3.14, 1e-9 | IEEE 754 double — the same rounding surprises as everywhere else |
str | "Ada" | Unicode text, immutable. No separate character type |
bool | True, False | A subclass of int: True + True really is 2 |
None | None | The absence of a value. Not zero, not "", not False |
complex | 3 + 4j | Built in, which says something about who designed the language |
Numbers behave predictably, with two divisions
Integers have no maximum: 2 ** 1000 is an ordinary number. Floats are the usual doubles, so 0.1 + 0.2 != 0.3 here exactly as it does in JavaScript — use decimal.Decimal for money and math.isclose for comparisons.
7 / 2 # 3.5 — true division, always a float
7 // 2 # 3 — floor division, rounds towards minus infinity
-7 // 2 # -4 — note: towards minus infinity, not towards zero
7 % 3 # 1 — and the result takes the sign of the divisor
-7 % 3 # 2 — which is different from C, and usually what you want
2 ** 10 # 1024 — power, not xor
divmod(7, 2) # (3, 1)
Truthiness has a short, exact list
That is the whole list. It is why if items: is the idiomatic way to ask "is this list non-empty", and why a function that returns 0 or "" can be mistaken for a failure if you test it with if result:.
For "is it missing?", test if result is None: — is compares identity, and None is a singleton, so is None is both correct and fast. Never == None.
False, None, 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
"", (), [], {}, set(), range(0) # every empty container
# plus any object whose __bool__ returns False, or whose __len__ returns 0
No implicit conversion between text and numbers
This is one of the real differences from JavaScript: Python refuses rather than guesses. int("3.7") is an error too — parsing a float and truncating are two decisions, so you make both: int(float("3.7")).
"3" + 4 # TypeError: can only concatenate str (not "int") to str
int("3") + 4 # 7
str(3) + "4" # "34"
"3" * 4 # "3333" — this one is defined, and means repetition
float("1e-3") # 0.001
int("ff", 16) # 255
Everything is an object
== asks about value, is asks about identity. CPython caches small integers and some short strings, which makes is accidentally work and then fail on a larger number — a classic beginner bug. Use is for None, True and False, and == for everything else.
x = 300
y = 300
x == y # True — same value
x is y # False — (usually) two different objects
a = 5
b = 5
a is b # True — small integers are cached; do not rely on this