Variables
A variable is a name that refers to a value. In Python you create one simply by assigning to it — there's no keyword and no type declaration. This lesson covers assignment, naming rules, multiple assignment, and what a variable really is under the hood.
Creating variables
city = "Lisbon" population = 545_000 is_capital = True print(city, population, is_capital)
Lisbon 545000 True
The = sign means "assign": the name on the left now refers to the value on the right. Underscores in numbers like 545_000 are only for readability.
Reassigning
A variable can be pointed at a new value at any time — even a value of a different type:
score = 10 score = score + 5 print(score) score = "fifteen" print(score)
15 fifteen
This flexibility is called dynamic typing. It's convenient, but changing what kind of value a name holds usually makes code confusing, so avoid it in practice.
Augmented assignment
count = 10
count += 5
count -= 3
count *= 2
count //= 5
print(count)
4
count += 5 is shorthand for count = count + 5. Python has no ++ or -- operators.
Multiple assignment
x, y, z = 1, 2, 3 print(x, y, z) a = b = 0 print(a, b) left, right = "L", "R" left, right = right, left print(left, right)
1 2 3 0 0 R L
The last example swaps two variables in one line — no temporary variable needed. This works through unpacking, covered in detail in lesson 26.
Naming rules
- Names can contain letters, digits and underscores, but can't start with a digit.
- They're case-sensitive:
ageandAgeare different. - They can't be reserved keywords like
if,class,for,None.
| Convention (PEP 8) | Example | Used for |
|---|---|---|
| snake_case | first_name, total_price | Variables and functions |
| PascalCase | ShoppingCart | Classes |
| UPPER_SNAKE_CASE | MAX_RETRIES | Constants (by convention only) |
| Leading underscore | _cache | "Internal — don't use from outside" |
Python has no true constants: MAX_RETRIES = 3 can still be reassigned. The capital letters are a signal to other programmers not to.
list, str, sum, max and input are built-in functions. Writing list = [1, 2] works, but then you can no longer call list() in that scope. Pick names like items or numbers instead.Variables are labels, not boxes
In Python, a variable doesn't contain a value — it's a name tag attached to an object. Two names can be attached to the same object:
a = [1, 2, 3] b = a b.append(4) print(a) print(a is b) c = [1, 2, 3, 4] print(a == c, a is c)
[1, 2, 3, 4] True True False
b = a doesn't copy the list; both names refer to one list, so changing it through b is visible through a. == compares values; is checks whether two names refer to the very same object. This matters for mutable types like lists and dictionaries (lesson 19).
Deleting a name
temp = 42 del temp print(temp)
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(temp)
^^^^
NameError: name 'temp' is not defined