Variables are containers for storing data. They can store single data types – such as numbers (integers and floats), text (strings), and true or false (boolean values) – or several pieces of data (lists, tuples, dictionaries, objects, and more). Data is assigned to a variable using the assignment operator, the equals sign. Here are a few examples.
pi = 3.14 yard = 36 title = "Between the World and Me" stop = True colors = ['red','yellow','blue']
The value on the right of the expression is assigned to the variable on the left of the equation. In the first expression, the value of 3.14 is assigned to the variable pi.
In this example, we can easily see what is stored inside of the variable because we have just assigned it. But oftentimes you will work with variables and don’t know what values they contain. Use the print method to show the contents of the variable in the console.
print(pi) print(yard) print(title) print(stop) print(colors)
Keep in mind that the assignment operator is not the same as “equals” in the mathematical sense. For one, values stored in a variable can be changed. Take a look at the example below.
age = 50 print(age) age = 60 print(age)
In this case, the value assigned to the variable age has changed from 50 to 60. Once a value has been overwritten, there is no way to retrieve that information. Thus is you may need the old value in a variable, you should save it to another variable before overwriting it.
As mentioned previously, variables can hold different data types. If we manually assign a value to a variable, then we can be confident of the data type. However, there are times we will work with variables and we are not sure what kind of data they contain. A useful method is the type function. This will let you know what data type is stored the variable. Here’s how the function works.
Notice that the function type is being called inside of the function print. This allows the type to be displayed in the console. Otherwise, the function will determine the type, but it will not be visible to you.
Variable names have certain rules. First, you want to make your variable names descriptive. Naming your variables a, b, c, d,… usually isn’t very informative. You’ll want to give them meaningful names, such as the ones I have shown above. You’ll also want to keep them fairly short.
Variables names must start with a letter or an underscore, and can only contain letters, numbers, and underscore characters. Variable names are also case sensitive, so Name and name are two different variables.