Variables and Data Types
~340 words ยท 2 min read
Understanding Python's Type System
Python uses dynamic typing, which means you never declare a variable's type explicitly. The interpreter infers the type at runtime from the value you assign. This makes Python concise and readable, but it also means a variable's type can change as the program runs.
The Core Built-in Types
Every Python value is one of these fundamental types:
intโ whole numbers like42or-7(arbitrary precision)floatโ decimal numbers like3.14strโ text, like"hello"boolโTrueorFalseNoneTypeโ the singletonNone, representing "no value"
count = 100 # int
price = 19.99 # float
name = "Ada" # str
active = True # bool
result = None # NoneType
Type Hints
Since Python 3.5, you can add optional type hints. They do not enforce types at runtime, but tools like mypy and your IDE use them to catch bugs early.
def greet(name: str) -> str:
return f"Hello, {name}"
Checking Types
Use type() to inspect a value's exact type, and isinstance() to test membership against a type or tuple of types. The latter is preferred because it respects inheritance.
type(42) # returns the int type
isinstance(42, int) # True
isinstance(42, (int, float)) # True (accepts a tuple)
Rule of thumb: prefer
isinstance()over comparingtype()for equality. It handles subclasses gracefully and accepts a tuple of allowed types.
String Formatting with f-strings
F-strings (Python 3.6+) are the idiomatic way to embed expressions inside text. They are fast, readable, and support format specifiers.
name = "World"
pi = 3.14159
msg = f"Hello, {name}! Pi is {pi:.2f}"
# msg == "Hello, World! Pi is 3.14"
Mutable vs Immutable
Some types are immutable โ once created, their value cannot change. int, float, str, and tuple are immutable; reassigning a string creates a new object. Lists and dicts are mutable and can be modified in place.
t = (1, 2, 3) # tuple - immutable
lst = [1, 2, 3] # list - mutable
lst.append(4) # OK, modifies in place