Python Variables
A variable is a name bound to a value. Python decides the type at runtime — you don't declare it.
Assigning
PYTHON
name = 'Ada' # str age = 36 # int active = True # bool ratio = 0.382 # float
Re-assigning changes the type
PYTHON
x = 1 x = 'hello' # legal; x was an int, now it's a str x = [1, 2, 3] # now a list
Multiple assignment
PYTHON
x = y = z = 0 # all three bound to 0 a, b = 1, 2 # tuple unpacking a, b = b, a # swap — no temp variable
Naming rules
- Letters, digits, underscores. Can't start with a digit.
- Case-sensitive —
ageandAgeare different. - Don't shadow built-ins: avoid
list,dict,str,id,typeas variable names.
Variables hold references
Assigning a list to a second name doesn't copy it. Both names point at the same object:
PYTHON
a = [1, 2, 3] b = a b.append(4) print(a) # [1, 2, 3, 4] — a saw the change
Tip: Use
type(x) at any time to see what type Python inferred. Or annotate with type hints (name: str = 'Ada') so IDEs and linters check it for you.Example
Example
name = 'Ada'
age = 36
active = True
print(f'{name} is {age} and active={active}')
Try it Yourself »
Exercise
Bind the name "x" to the integer 42.
x
42
The assignment operator.
Discussion
Loading…