Python Variables
A variable is a name that refers to a value. Variables let a program remember information, such as a user's name, a price or a score, and use it again later. Almost every line of real Python code uses them.
Creating variables
You create a variable the moment you assign a value to it with the = sign. The name goes on the left and the value on the right. Unlike some languages, Python doesn't make you declare a type first.
age = 21 # a whole number
price = 1499.50 # a decimal number
name = "Wanjiku" # text
is_student = True # a yes/no value
print(name, "is", age, "years old")
print("Price:", price)
Read age = 21 as "age refers to 21" or "store 21 in age", not "age equals 21". The = sign means assignment, not mathematical equality. (Python prints 1499.50 as 1499.5 because the trailing zero doesn't change the number.)
Variables can change
You can reassign a variable at any time. The old value is simply replaced. A variable can even switch to a different kind of value, because Python is dynamically typed: the type belongs to the value, not to the name.
balance = 500 print(balance) balance = balance + 250 # deposit 250 print(balance) balance = "closed" # now it refers to text print(balance)
In balance = balance + 250, Python first works out the right-hand side using the current value (500 + 250), then stores the answer (750) back in balance. Python also has a shorthand for this: balance += 250. You'll meet it on the Operators page.
Naming rules
Python enforces a few rules for variable names:
- Names may contain letters, digits and underscores:
total_sales,item2,_hidden. - A name cannot start with a digit:
2itemsis invalid. - No spaces or symbols such as
-,@or!:monthly-rentis invalid. - Names are case-sensitive:
Score,scoreandSCOREare three different variables. - You can't use Python keywords, words reserved for the language such as
if,for,while,class,def,TrueandNone.
| Valid names | Invalid names | Why invalid |
|---|---|---|
first_name | first name | contains a space |
county2 | 2county | starts with a digit |
is_paid | is-paid | Python reads - as minus |
class_name | class | a reserved keyword |
Follow the PEP 8 style: use snake_case (lowercase words joined by underscores) and descriptive names. monthly_rent tells a reader far more than x or mr. Values that should never change, called constants, are written in capitals by convention, for example VAT_RATE = 16. Python doesn't stop you changing them; the capitals are a signal to other programmers.
Assigning several variables at once
Python lets you assign multiple variables in one line. The number of names on the left must match the number of values on the right.
x, y, z = 10, 20, 30 # one value each a = b = c = 0 # the same value for all three first, last = "Brian", "Otieno" print(x, y, z) print(a, b, c) print(first, last)
A neat trick is swapping two values without a temporary variable:
morning = "chai" evening = "coffee" morning, evening = evening, morning print(morning, evening)
Checking a variable's type
The built-in type() function tells you what kind of value a variable currently refers to. You'll explore every type on the Data Types page.
score = 87 average = 87.5 grade = "A" print(type(score)) print(type(average)) print(type(grade))
Variables are labels, not boxes
It helps to picture a variable as a name tag attached to a value, rather than a box that holds it. Two names can point at the same value:
school = "Alliance" favourite = school # both names now refer to the same text school = "Mang'u" # move the school tag to a new value print(favourite) print(school)
Reassigning school moved that one tag; favourite still points at the original value. This mental model becomes important when you work with lists, which can be changed in place.
school moves only that tag to a new value; favourite keeps pointing at "Alliance".Using a variable before assigning it, or misspelling its name, raises a NameError. If you write total = 100 and later print(totl), Python complains that totl is not defined (and often suggests the name you probably meant). Check spelling and capital letters first.
Avoid naming variables after built-in functions, such as print = 5, type = "A" or input = 10. It's allowed, but it hides the real function, and the next time you call print() your program crashes.
Key points
- Create a variable by assigning a value with
=; no type declaration is needed. - Variables can be reassigned at any time, even to a different type.
- Names use letters, digits and underscores, can't start with a digit and are case-sensitive.
- Use descriptive snake_case names, and capitals for constants.
type()shows what kind of value a variable refers to.
Tip: use the ← and → keys to move between pages.
