Python Variables and Data Types: Names, Types, and Type Hints
What you’ll learn
Section titled “What you’ll learn”- How Python’s dynamic type system works and what it means for your code.
- The built-in primitive types:
int,float,bool,str,bytes, andNone. - How to annotate variables and functions with type hints.
- Mutability: which types can change and which cannot.
- Practical naming conventions and common pitfalls.
Summary
Section titled “Summary”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+).
Creating variables
Section titled “Creating variables”Python variables come into existence when you first assign them. No declaration keyword (var, let, const, int) is needed.
order_id = "ORD-001" # strquantity = 12 # intunit_price = 49.95 # floatis_shipped = False # boolcustomer_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.08MAX_RETRIES = 3Python does not enforce immutability on ALL_CAPS names; this is a social contract with other developers on the team.
Multiple assignment
Section titled “Multiple assignment”# Assign the same value to multiple namesx = y = z = 0
# Unpack from a sequence (works with any iterable)first, *rest = ["ORD-001", "ORD-002", "ORD-003"]print(first) # ORD-001print(rest) # ['ORD-002', 'ORD-003']
# Swap without a temporary variablea, b = 10, 20a, b = b, aprint(a, b) # 20 10Built-in primitive types
Section titled “Built-in primitive types”Python integers have arbitrary precision — there is no overflow. 2 ** 1000 is a valid operation.
count = 42big = 1_000_000 # underscores are ignored: 1000000hex_val = 0xFF # 255binary = 0b1010 # 10octal = 0o17 # 15
print(type(count)) # <class 'int'>print(10 // 3) # 3 (floor division)print(10 % 3) # 1 (modulo)print(2 ** 10) # 1024Python floats are IEEE 754 double-precision (64-bit). They are subject to the same rounding issues as in every other language.
price = 49.95tax = price * 0.08print(tax) # 3.9959999999999996 — floating-point imprecision
# For money, use the decimal modulefrom decimal import Decimalprice_d = Decimal("49.95")tax_d = price_d * Decimal("0.08")print(tax_d) # 3.9960 — exactNever 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 = Trueis_deleted = False
print(isinstance(True, int)) # Trueprint(True + True) # 2
# Falsy values: False, 0, 0.0, "", [], {}, set(), None# Everything else is truthyprint(bool("")) # Falseprint(bool("hello"))# Trueprint(bool(0)) # Falseprint(bool([])) # FalseStrings are immutable sequences of Unicode characters.
name = "OrdersPortal"multi = """Line oneLine two"""
# f-strings (Python 3.6+): the standard for string interpolationorder_id = "ORD-001"amount = 149.99message = f"Order {order_id}: ${amount:.2f}"print(message) # Order ORD-001: $149.99
# Common string methodsprint(" 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")) # Trueprint("hello".replace("l", "L")) # "heLLo"
# Strings are immutable: methods return new stringss = "hello"s.upper() # returns "HELLO" but s is still "hello"s = s.upper() # rebind s to the new stringbytes and bytearray
Section titled “bytes and bytearray”bytes is an immutable sequence of integers 0–255. Use it for binary data, encoding, and network I/O.
raw = b"hello" # bytes literalencoded = "hello".encode("utf-8") # str → bytesdecoded = raw.decode("utf-8") # bytes → str
# bytearray is the mutable variantbuf = 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 argumentsdef process(order_id: str, notes: str | None = None) -> None: if notes is not None: print(f"Note: {notes}")Dynamic typing in practice
Section titled “Dynamic typing in practice”x = 42print(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
Section titled “Type hints”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 annotationsorder_id: str = "ORD-001"quantity: int = 12price: float = 49.95is_active: bool = Truenotes: str | None = None # Union type (Python 3.10+ syntax)
# Function annotationsdef 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 directlydef 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.
Checking types at runtime
Section titled “Checking types at runtime”x = 42
# isinstance checks the type of an objectprint(isinstance(x, int)) # Trueprint(isinstance(x, (int, float))) # True — matches either
# type() returns the exact typeprint(type(x) is int) # Trueprint(type(x) is float) # FalsePrefer isinstance over type(x) == int. isinstance respects inheritance, so isinstance(True, int) is True (because bool is a subclass of int).
Mutability
Section titled “Mutability”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 objecta = "hello"b = aa = a + " world" # a now refers to a new stringprint(b) # "hello" — b is unchanged
# Mutable: mutating affects all references to the same objectlist_a = [1, 2, 3]list_b = list_a # both point to the SAME listlist_a.append(4)print(list_b) # [1, 2, 3, 4] — affected because it's the same object
# To copy a list: use list() or slicinglist_c = list_a[:] # shallow copyCommon mistakes
Section titled “Common mistakes”- Mutable default arguments.
def f(items=[])creates the list once at function definition. All calls share it. Usedef f(items=None): items = items or []. - Using
==to compare withNone. Useis Noneandis not None. Overloaded__eq__can makex == Nonereturn unexpected results. - Using
floatfor money. IEEE 754 rounding errors accumulate. Usedecimal.Decimalor integer cents. - Shadowing built-in names.
list = [1, 2, 3]replaces the built-inlisttype with a list object in the local scope. Avoid naming variables after built-ins (list,dict,str,id,type,input,print).
Interview questions
Section titled “Interview questions”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).
Key takeaways
Section titled “Key takeaways”- 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 Noneto check forNone. - Never use
floatfor monetary amounts — usedecimal.Decimalor integer cents.
Related pages
Section titled “Related pages”- Python control flow — the next article in this series
- Python type hints feature guide — advanced type hint patterns
- Python basics quick reference — syntax at a glance
Official references
Section titled “Official references”- Python docs: Built-in Types — complete type reference
- PEP 484 — type hints specification
- PEP 526 — variable annotation syntax
- decimal module — exact decimal arithmetic