Variables & Assignment
Variables are named references to values stored in memory. In Python, variables are dynamically typed โ you don't declare a type, and a variable can point to different types throughout its life.
Basic Assignment
Assignment uses the = operator. The variable name goes on the left, the value on the right:
Python variables are references (pointers) to objects, not boxes containing values. When you do x = 42, Python creates an integer object with value 42 and makes x point to it.
Naming Conventions
Python follows PEP 8 naming conventions. Following them makes your code instantly readable to other Python developers:
Valid vs Invalid Names
Reserved keywords you cannot use as variable names:
False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
Multiple Assignment
Python supports several forms of multiple assignment:
Augmented Assignment Operators
Augmented assignment modifies a variable in place (or rather, creates a new object and rebinds the name):
Constants by Convention
Python has no built-in constant mechanism โ you can always reassign a variable. The community convention is to use UPPER_SNAKE_CASE for values that shouldn't change:
The Walrus Operator (:=)
Introduced in Python 3.8, the walrus operator (:=) assigns a value to a variable as part of an expression. This is useful when you want to both assign and test a value:
Common walrus operator patterns:
The walrus operator is intentionally different from = to avoid confusion. Use it when it genuinely reduces repetition โ don't overuse it.
Variable Scope Preview
Variables have different scopes depending on where they're defined:
We'll explore scope in depth when we cover functions.
Deleting Variables
You can delete a variable with del:
del removes the name binding, not necessarily the object (which gets garbage collected when there are no more references to it).
Knowledge Check
What naming convention does PEP 8 recommend for regular Python variables?
What does this code print? x, y = 1, 2; x, y = y, x; print(x, y)
What is the walrus operator (:=) used for?