A Python variable stores a value you can use and change later — the same idea from Intro to Programming, with Python's own syntax, which is about as minimal as it gets.
No $ sigil, no keyword — just a name and a value:
name = "Amit"
age = 21
print(f"{name} is {age} years old.")The f before the string in f"{name} is {age}..." is an f-string — Python's way of embedding variables directly in a string. You'll look at f-strings properly in the Strings lesson.
| Rule | Example |
|---|---|
| Must start with a letter or underscore (never a number) | _id — valid, 1id — invalid |
| Can contain letters, numbers, and underscores after that | user_2 — valid |
| No spaces or hyphens allowed | user name — invalid |
| Case-sensitive | Name and name are different variables |
| Convention: snake_case, all lowercase | first_name, not firstName |
snake_case, not camelCase
snake_case (lowercase words joined by underscores) is the standard Python naming convention for variables and functions. camelCase (capitalizing the first letter of each word after the first, like firstName) is common in several other languages, but not in Python. It's a convention, not a rule the language enforces, but real Python code follows it consistently.
You never declare a variable's type — Python figures it out from the value, and a variable can hold a different type later:
value = 10 # an integer
value = "ten" # now a string — perfectly legalPython has no const keyword and no built-in way to declare a value as fixed — there's no way to make a variable truly unchangeable. Instead, the convention is to name a value that shouldn't be changed in UPPER_SNAKE_CASE, as a signal to anyone reading the code:
MAX_UPLOAD_SIZE = 5242880 # 5 MB — nothing stops this from being reassigned,
# but the ALL_CAPS name says "please don't"Python can also assign multiple variables in a single line:
x, y, z = 1, 2, 3
print(x, y, z) # 1 2 3
# Same value to several names at once:
a = b = c = 0
print(a, b, c) # 0 0 0This also produces Python's well-known one-line variable swap, with no temporary third variable needed:
a = 1
b = 2
a, b = b, a
print(a, b) # 2 1