A variable is a placeholder for information. It is a name you give to a piece of data, so that your program can store that data, refer back to it later, and replace it while the program is running.
Variables are used in a very similar way to letters in algebra: the name stands in for the value, and the value it stands for can be different every time.
Putting a piece of data into a variable is called assignment, and it is done
with a single = symbol. The variable name goes on the left, the data goes
on the right:
fav_colour = "blue"
That line creates a variable called fav_colour and stores the string "blue"
inside it. It helps to read the = as “gets the value” rather than as “equals”:
the data on the right is dropped into a box that carries the name on the left.
A variable holds exactly one piece of information at a time. Assign something new to the same variable and the old value is gone:
fav_colour = "blue"
fav_colour = "green"
After those two lines, fav_colour contains "green". Nothing anywhere still
remembers "blue".
Once a variable has a value, you use its name whenever you want that information back. Writing the name without speech marks tells Python to look inside the box and use whatever it finds there:
fav_colour = "blue"
print(fav_colour)
blue
Watch the speech marks closely, because they change everything.
print(fav_colour) outputs the contents of the variable, while
print("fav_colour") outputs the text fav_colour.
Run the code below. Then change the value that is assigned to the variable, run it again, and check that the output follows along.
fav_colour = "blue" print(fav_colour)
You can call a variable almost anything you like, but some of the rules below are enforced by Python and the rest keep your code readable for other people (including yourself, next week).
| Rule | Example |
|---|---|
| Give the variable a meaningful name, so the name itself tells you what is stored in it | fav_colour, not x |
| No spaces in the name | fav_colour, not fav colour |
| The name starts with a lower case letter | fav_colour, not Fav_colour |
| Two variables can never have the same name | first_name and last_name, not name twice |
| If the name is more than one word long, write it in lower case with an underscore between each word | this_is_an_example_variable_name |
That last convention, writing every word in lower case and joining them with underscores, is known as snake case. The underscores stand in for the spaces a variable name is not allowed to contain.
Python matches variable names exactly, capital letters included. fav_colour,
Fav_colour and FAV_COLOUR are three different names, and asking for one you
never created gives you a NameError instead of a value. Type the name the
same way every single time.