Variables
A variable is a name that stores a value. You create one with =, then use the name to get the value back later.
Creating a variable
score = 10name = "Alice"print(score)print(name)Put the name on the left of = and the value on the right. print(score) prints the stored value, 10.
Using a variable
Once a value is stored, use the name anywhere you would use the value:
score = 10bonus = 5total = score + bonusprint(total)Python reads score and bonus, adds them, and stores 15 in total.
Changing a variable
You can store a new value in a variable at any time. The name always holds whatever you stored in it last:
score = 10score = score + 5print(score)score = score + 5 reads the old value (10), adds 5, and stores 15
back under the same name.
Naming rules
- Use lowercase letters, digits and underscores, such as
total_pointsorroll_2. - Start with a letter or underscore, not a digit.
- Do not use a Python keyword such as
if,fororreturnas a name. - Names are case-sensitive:
scoreandScoreare different names.
Case-sensitivity catches people out. These are two separate variables:
score = 10Score = 99print(score)print(Score)See also: Data types and operations, String Formatting.
Your turn
Add two lines: store score + bonus in a new variable called total, then
print it.
15
score = 12bonus = 3# add two lines: make a total variable, then print itAdvanced reading
- Augmented assignment — update a variable with
+=and-=, and swap two values in one line. - Names and references — when two names share one list, and how
isandcopy()help.