Skip to main content

Basic Python Syntax and Object Model

Python source is organized into expressions that produce values and statements that control binding, execution, and definitions. Indentation delimits suites after headers ending in :.

temperature_c = 21.5
if temperature_c < 0:
state = "frozen"
else:
state = "liquid"

Names bind objects

Assignment binds a name; it does not declare a storage box or copy the value:

first = [1, 2]
second = first
second.append(3)
assert first == [1, 2, 3]

Use .copy(), slicing, or a deeper-copy strategy when independent mutable state is required. Whether an operation mutates depends on the object's type and API.

Built-in value families

  • numeric: int, float, complex, bool;
  • text and binary: str, bytes, bytearray;
  • sequences: list, tuple, range;
  • mappings and sets: dict, set, frozenset;
  • absence sentinel: None.

These categories imply different protocols. For example, a string is immutable, a list is mutable, and dictionary keys must be hashable.

Operators and comparison

/ performs true division; // performs floor division; % gives the matching remainder. Use == for value equality and is for identity, normally with singletons such as None:

if result is None:
handle_missing_result()

Conversion is a boundary

Constructors such as int(text), float(text), and str(value) request a conversion and may raise an exception. Do not assume user or file input has the desired form:

try:
quantity = int(raw_quantity)
except ValueError as error:
raise ValueError("quantity must be an integer") from error

Namespaces and imports

Imports bind module objects or selected names in the current namespace:

from pathlib import Path

config_path = Path("config.json")

Prefer explicit imports and avoid wildcard imports; ownership and name origin should remain visible.

Sources