Skip to content

Python Variables and Data Types: Names, Types, and Type Hints

  • How Python’s dynamic type system works and what it means for your code.
  • The built-in primitive types: int, float, bool, str, bytes, and None.
  • How to annotate variables and functions with type hints.
  • Mutability: which types can change and which cannot.
  • Practical naming conventions and common pitfalls.

In Python, a variable is a name that refers to an object. The object has a type; the name does not. You can rebind a name to a different type at any time — Python will not stop you. This is dynamic typing. It is fast and flexible for small scripts but requires discipline and type hints for production codebases.

Save all examples as a .py file and run with python examples.py (Python 3.9+).

Python variables come into existence when you first assign them. No declaration keyword (var, let, const, int) is needed.

order_id = "ORD-001" # str
quantity = 12 # int
unit_price = 49.95 # float
is_shipped = False # bool
customer_name = None # NoneType (absence of a value)

Variables are case-sensitive. order_id, Order_Id, and ORDER_ID are three different names. The convention is snake_case for all variables and functions. Constants — values that should not change — are written in ALL_CAPS by convention:

TAX_RATE = 0.08
MAX_RETRIES = 3

Python does not enforce immutability on ALL_CAPS names; this is a social contract with other developers on the team.

# Assign the same value to multiple names
x = y = z = 0
# Unpack from a sequence (works with any iterable)
first, *rest = ["ORD-001", "ORD-002", "ORD-003"]
print(first) # ORD-001
print(rest) # ['ORD-002', 'ORD-003']
# Swap without a temporary variable
a, b = 10, 20
a, b = b, a
print(a, b) # 20 10

Python integers have arbitrary precision — there is no overflow. 2 ** 1000 is a valid operation.

count = 42
big = 1_000_000 # underscores are ignored: 1000000
hex_val = 0xFF # 255
binary = 0b1010 # 10
octal = 0o17 # 15
print(type(count)) # <class 'int'>
print(10 // 3) # 3 (floor division)
print(10 % 3) # 1 (modulo)
print(2 ** 10) # 1024

Python floats are IEEE 754 double-precision (64-bit). They are subject to the same rounding issues as in every other language.

price = 49.95
tax = price * 0.08
print(tax) # 3.9959999999999996 — floating-point imprecision
# For money, use the decimal module
from decimal import Decimal
price_d = Decimal("49.95")
tax_d = price_d * Decimal("0.08")
print(tax_d) # 3.9960 — exact

Never use float for monetary amounts. Use Decimal or store amounts as integer cents.

bool is a subclass of int. True == 1 and False == 0 are both true.

is_active = True
is_deleted = False
print(isinstance(True, int)) # True
print(True + True) # 2
# Falsy values: False, 0, 0.0, "", [], {}, set(), None
# Everything else is truthy
print(bool("")) # False
print(bool("hello"))# True
print(bool(0)) # False
print(bool([])) # False

Strings are immutable sequences of Unicode characters.

name = "OrdersPortal"
multi = """Line one
Line two"""
# f-strings (Python 3.6+): the standard for string interpolation
order_id = "ORD-001"
amount = 149.99
message = f"Order {order_id}: ${amount:.2f}"
print(message) # Order ORD-001: $149.99
# Common string methods
print(" hello ".strip()) # "hello"
print("hello world".split(" ")) # ['hello', 'world']
print(",".join(["a", "b", "c"])) # "a,b,c"
print("Hello World".lower()) # "hello world"
print("ORD-001".startswith("ORD")) # True
print("hello".replace("l", "L")) # "heLLo"
# Strings are immutable: methods return new strings
s = "hello"
s.upper() # returns "HELLO" but s is still "hello"
s = s.upper() # rebind s to the new string

bytes is an immutable sequence of integers 0–255. Use it for binary data, encoding, and network I/O.

raw = b"hello" # bytes literal
encoded = "hello".encode("utf-8") # str → bytes
decoded = raw.decode("utf-8") # bytes → str
# bytearray is the mutable variant
buf = bytearray(b"hello")
buf[0] = ord("H")
print(buf) # bytearray(b'Hello')

None is a singleton representing the absence of a value. It is Python’s equivalent of null in C# or JavaScript.

result = None
# Check with 'is', not '=='
if result is None:
print("No result yet")
# Common: optional function arguments
def process(order_id: str, notes: str | None = None) -> None:
if notes is not None:
print(f"Note: {notes}")
x = 42
print(type(x)) # <class 'int'>
x = "now a string"
print(type(x)) # <class 'str'>
x = [1, 2, 3]
print(type(x)) # <class 'list'>

Each assignment rebinds the name x to a different object. The original objects may be garbage-collected if nothing else refers to them.

Type hints (PEP 484) let you annotate variables and function signatures. They are ignored by the Python runtime but checked by tools like mypy and Pyright, and read by IDEs.

# Variable annotations
order_id: str = "ORD-001"
quantity: int = 12
price: float = 49.95
is_active: bool = True
notes: str | None = None # Union type (Python 3.10+ syntax)
# Function annotations
def calculate_total(subtotal: float, tax_rate: float = 0.08) -> float:
return round(subtotal * (1 + tax_rate), 2)
# From Python 3.9+: use built-in generics directly
def get_pending_orders() -> list[str]:
return ["ORD-001", "ORD-002"]
def get_order_map() -> dict[str, float]:
return {"ORD-001": 108.0}

Type hints are documentation that tools can verify. Use them in all non-trivial production code.

x = 42
# isinstance checks the type of an object
print(isinstance(x, int)) # True
print(isinstance(x, (int, float))) # True — matches either
# type() returns the exact type
print(type(x) is int) # True
print(type(x) is float) # False

Prefer isinstance over type(x) == int. isinstance respects inheritance, so isinstance(True, int) is True (because bool is a subclass of int).

An object is mutable if its value can change after creation. This matters when you pass objects between functions.

Type Mutable
int, float, bool No
str No
bytes No
tuple No
list Yes
dict Yes
set Yes
bytearray Yes
# Immutable: reassignment creates a new object
a = "hello"
b = a
a = a + " world" # a now refers to a new string
print(b) # "hello" — b is unchanged
# Mutable: mutating affects all references to the same object
list_a = [1, 2, 3]
list_b = list_a # both point to the SAME list
list_a.append(4)
print(list_b) # [1, 2, 3, 4] — affected because it's the same object
# To copy a list: use list() or slicing
list_c = list_a[:] # shallow copy
  • Mutable default arguments. def f(items=[]) creates the list once at function definition. All calls share it. Use def f(items=None): items = items or [].
  • Using == to compare with None. Use is None and is not None. Overloaded __eq__ can make x == None return unexpected results.
  • Using float for money. IEEE 754 rounding errors accumulate. Use decimal.Decimal or integer cents.
  • Shadowing built-in names. list = [1, 2, 3] replaces the built-in list type with a list object in the local scope. Avoid naming variables after built-ins (list, dict, str, id, type, input, print).

1. What does it mean that Python is dynamically typed? Variables are names that refer to objects. The object has a type; the name does not. You can rebind a name to any type at any time. The type of an expression is determined at runtime, not compile time. This contrasts with C# or Java where the type is declared and enforced at compile time.

2. What is the difference between is and == in Python? == calls __eq__ and checks value equality — two different objects with equal contents can be ==. is checks identity — both sides must reference the exact same object in memory. None is a singleton, so x is None is the idiomatic check; x == None works but can be fooled by a class with a custom __eq__.

3. Senior scenario: an OrdersPortal service processes 10 million order records per day. Each record has an amount field stored as a Python float. A financial auditor reports that daily totals are off by a few cents. What is happening and how do you fix it? IEEE 754 floating-point arithmetic cannot represent most decimal fractions exactly. 0.1 + 0.2 in Python evaluates to 0.30000000000000004. Summing millions of floats accumulates these rounding errors. Fix: store amounts as integer cents (100 = $1.00), or use decimal.Decimal with ROUND_HALF_UP throughout. If migrating, convert stored floats to Decimal by going through a string representation: Decimal(str(amount)), not Decimal(amount) (the latter preserves the float’s imprecision).

  • Variables are names that refer to objects; the type belongs to the object, not the name.
  • Use type hints in all non-trivial code — they are documentation tools can verify.
  • Immutable types (str, int, tuple) cannot change; mutable types (list, dict, set) can.
  • Use is None / is not None to check for None.
  • Never use float for monetary amounts — use decimal.Decimal or integer cents.