A variable is a name bound to an object. Every object has an identity, a type and a value.
Built-in types
| Type | Example | Mutable? |
|---|---|---|
int | 42, -7, 10**100 (unlimited size) | No |
float | 3.14, 1e-9 (64-bit IEEE 754) | No |
complex | 2 + 3j | No |
bool | True, False (a subclass of int) | No |
str | 'hi', "hi", '''multi''' | No |
NoneType | None — the single “no value” object | No |
list / dict / set | [1, 2], {'a': 1}, {1, 2} | Yes |
tuple / frozenset | (1, 2), frozenset({1}) | No |
x = 10
print(type(x)) # <class 'int'>
x = "now a string" # same name, different object and type
print(isinstance(x, str)) # True
print(True + True) # 2Operators at a glance
Arithmetic + - * / // % **, comparison == != < <= > >= (chainable), logical and or not, identity is, membership in, bitwise & | ^ ~ << >> and the walrus :=. The next topic, Operators & Precedence, covers each one in depth.
print(7 / 2, 7 // 2, 7 % 2, -7 // 2) # 3.5 3 1 -4
print(2 ** 10, divmod(17, 5)) # 1024 (3, 2)
print(0 < 5 < 10) # True
print("" or "default", 0 and 99) # default 0
if (n := len("hello")) > 3:
print(n) # 5== vs is
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b, a is b, a is c) # True False TrueTruthiness
In a condition, every object is truthy except these falsy values:
False · None · 0, 0.0, 0j · '' · [] · () · {} · set() · range(0)
items = []
if not items: # idiomatic emptiness check
print("empty") # empty
print(bool("0"), bool(0)) # True FalseType conversion
print(int("42") + 1, float("2.5"), str(99) + "!") # 43 2.5 99!
print(int(3.99), round(2.5), round(3.5)) # 3 2 4
print(int("ff", 16), bin(10), hex(255)) # 255 0b1010 0xff