Python Variables
A variable is a name that refers to a value. You create one simply by assigning to it with = — there is no var or let keyword and no type declaration.
Creating variables
greeting = "Xin chào"
year = 2025
pi = 3.14159
print(greeting)
print(year)
print(pi)Xin chào
2025
3.14159
A variable comes into existence the moment you first assign to it. Using a name before assigning it raises a NameError.
Variables can change type
Python is dynamically typed: the value has a type, the name does not. The same name can point to an integer now and a string later:
box = 10
print(box, type(box))
box = "ten"
print(box, type(box))10 <class 'int'>
ten <class 'str'>
Tip: Being allowed to do this doesn't mean you should. A variable that keeps one kind of value is much easier to follow.
Naming rules
| Rule | Valid | Invalid |
|---|---|---|
Must start with a letter or _ |
total, _hidden |
2nd_place |
May contain letters, digits, _ |
player2_score |
player-score |
| Case-sensitive | name and Name differ |
— |
| Can't be a keyword | class_name |
class, for, if |
By convention Python uses snake_case for variables and functions: max_speed, user_name. Names written in ALL_CAPS signal a constant — a value you intend never to change, like MAX_RETRIES = 3. (Python won't stop you from changing it; it is a promise between programmers.)
Assigning several variables at once
You can assign multiple names in one line. The values are matched up left to right:
x, y, z = 1, 2, 3
print(x, y, z)
a = b = c = 0
print(a, b, c)
# Swapping two values needs no temporary variable
left, right = "L", "R"
left, right = right, left
print(left, right)1 2 3
0 0 0
R L
Unpacking a collection
If you have a list or tuple, you can unpack its items straight into variables, as long as the counts match:
point = (4, 7)
px, py = point
print("x =", px, "y =", py)
first, *rest = [10, 20, 30, 40]
print(first)
print(rest)x = 4 y = 7
10
[20, 30, 40]
The * in *rest collects "everything else" into a list.
Variables are labels, not boxes
A helpful mental model: a variable is a label stuck on an object. Assigning one variable to another sticks a second label on the same object rather than copying it. For numbers and strings this rarely matters, but for lists it does:
original = [1, 2, 3]
alias = original
alias.append(4)
print(original)
print(alias is original)[1, 2, 3, 4]
True
Both names refer to one list, so changing it through alias is visible through original. You'll see how to make real copies in the Lists lesson.
Deleting a variable
del removes a name. After that, using it is an error:
temp = 99
del temp
try:
print(temp)
except NameError as err:
print("Error:", err)Error: name 'temp' is not defined
Test yourself
Which of these is a valid variable name?
- 2fast
- my-name
- user_name
- for
After a, b = 5, 9 and then a, b = b, a, what is a?
- 5
- 9
- 14
- An error
What naming style is conventional for Python variables?
- camelCase
- PascalCase
- snake_case
- kebab-case