Variable Assignment
name = valueusername = "alice"
age = 30
is_active = True# alice, 30, TrueNote Python variables are references to objects, not fixed memory boxes. No declaration keyword is needed.
Python · 8 entries
name = valueusername = "alice"
age = 30
is_active = True# alice, 30, TrueNote Python variables are references to objects, not fixed memory boxes. No declaration keyword is needed.
name: type = valueprice: float = 19.99
items: list[str] = ["apple", "bread"]
user_map: dict[str, int] = {"alice": 1}# No runtime enforcement — hints are for tools and readersNote Type hints do not prevent wrong types at runtime. Use mypy or pyright for static checking. Since 3.12, you can use the new type statement for aliases.
a, b, c = val1, val2, val3x, y, z = 10, 20, 30
first, *rest = [1, 2, 3, 4, 5]
print(first, rest)1 [2, 3, 4, 5]Note The starred variable (*rest) captures remaining items as a list. Only one starred variable is allowed per assignment.
type(obj)
isinstance(obj, ClassName)score = 95.5
print(type(score))
print(isinstance(score, (int, float)))<class 'float'>
TrueNote Prefer isinstance() over type() == because isinstance handles subclasses correctly. The second arg can be a tuple of types.
variable = Noneresult = None
if result is None:
print("No result yet")
# Common pattern: optional return
def find_user(user_id: int) -> str | None:
return NoneNo result yetNote Always compare to None with 'is' or 'is not', never == or !=. None is a singleton object.
UPPER_SNAKE_CASE = valueMAX_RETRIES = 3
BASE_URL = "https://api.example.com"
PI = 3.14159Note Python has no true constants. ALL_CAPS naming is a convention that signals 'do not reassign'. The typing.Final hint can be checked by type checkers.
name = value1
name = value2 # different type is alloweddata = 42
print(type(data))
data = "now a string"
print(type(data))<class 'int'>
<class 'str'>Note Python is dynamically typed, so a variable can be rebound to any type. Type hints help catch accidental rebinding via static analysis.
type AliasName = existing_typetype UserId = int
type Coordinate = tuple[float, float]
type UserMap = dict[UserId, str]
position: Coordinate = (40.71, -74.01)Note The type statement (Python 3.12+) replaces TypeAlias from typing. It supports lazy evaluation and generic parameters.