Variables & Types
Variables and dynamic typing
Section titled “Variables and dynamic typing”In Python you assign a value to a name — no type declaration needed. The variable’s type is determined by the object it currently references, not by a declaration.
x = 10 # x references an intx = "hello" # x now references a str — perfectly validx = [1, 2, 3] # x now references a listThis is called dynamic typing. The type travels with the object, not the variable name.
Built-in scalar types
Section titled “Built-in scalar types”Python ships with four scalar types you will use in every program:
| Type | Literal example | Notes |
|---|---|---|
int | 42, -7, 0 | Arbitrary precision — never overflows |
float | 3.14, -0.5 | IEEE 754 double precision |
str | "hello", 'world' | Immutable Unicode sequence |
bool | True, False | Subclass of int; True == 1, False == 0 |
There is also None — a singleton that represents the absence of a value.
None has its own type, NoneType, and there is exactly one None object in the entire Python process.
Always test for it with is None, never == None.
Checking types at runtime
Section titled “Checking types at runtime”type() returns the exact type of an object.
isinstance() tests whether an object is an instance of a type or any of its subclasses.
age = 30print(type(age)) # <class 'int'>print(isinstance(age, int)) # Trueprint(isinstance(True, int)) # True — bool is a subclass of intType conversions
Section titled “Type conversions”Python does not silently coerce types. You convert explicitly using the type name as a function:
n = int("42") # str -> intf = float("3.14") # str -> floats = str(100) # int -> strb = bool(0) # int -> bool -> FalseIf the conversion is impossible, Python raises a ValueError:
int("hello") # ValueError: invalid literal for int()Truthiness
Section titled “Truthiness”Every Python object has a boolean interpretation used in if and while conditions.
The following values are falsy — everything else is truthy:
False,None- Zero:
0,0.0,0j - Empty containers:
"",[],{},(),set()
name = ""if name: print("has name")else: print("name is empty") # this branch runsFull runnable demo
Section titled “Full runnable demo”age: int = 30price: float = 9.99greeting: str = "Hello"active: bool = Truenothing = None
print(type(age))print(type(price))print(type(greeting))print(type(active))print(type(nothing))
x = int("42")y = float("3.14")z = str(100)print(x, y, z)
falsy_values = [0, "", None, False, [], 0.0]for v in falsy_values: print(f"bool({v!r}) = {bool(v)}")Loading Python runtime (first run only)…