Skip to content

Variables & Types

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 int
x = "hello" # x now references a str — perfectly valid
x = [1, 2, 3] # x now references a list

This is called dynamic typing. The type travels with the object, not the variable name.

Python ships with four scalar types you will use in every program:

TypeLiteral exampleNotes
int42, -7, 0Arbitrary precision — never overflows
float3.14, -0.5IEEE 754 double precision
str"hello", 'world'Immutable Unicode sequence
boolTrue, FalseSubclass 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.

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 = 30
print(type(age)) # <class 'int'>
print(isinstance(age, int)) # True
print(isinstance(True, int)) # True — bool is a subclass of int

Python does not silently coerce types. You convert explicitly using the type name as a function:

n = int("42") # str -> int
f = float("3.14") # str -> float
s = str(100) # int -> str
b = bool(0) # int -> bool -> False

If the conversion is impossible, Python raises a ValueError:

int("hello") # ValueError: invalid literal for int()

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 runs
age: int = 30
price: float = 9.99
greeting: str = "Hello"
active: bool = True
nothing = 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)}")
What is dynamic typing in Python?
Which of the following is falsy in Python?
How should you test whether a variable holds None?
What does `bool` inherit from in Python?