What are variables?
In programming, variables are storage locations that are used to store information that can later be referenced and manipulated. You can consider a variable as a sort of a container where you store an information that can later be accessed with the variable name.
In Python, variables are created when they are first assigned values. Values are assigned using the assignment operator (=). For example, to create a variable named x and store the numeric value of 3 in it, you can use the following command:
x = 3
The command above does three things:
1. Creates an object that will represent the value 3.
2. Creates the variable x.
3. Links the variable x to the new object 3.
You can now use the variable x in your code. For example, to print the content of the variable, you can use the following command:
>>> print (x) 3
Notice how you didn’t need to write quotes around the variable name. When you want to print the content of a variable, quotes are not used. Consider what would happen if you use quotes:
>>> print ('x') x
Python considers the text inside the quotes to be a string and not a variable name. That is why the letter x was printed, and not the content of the variable x.
Once declared, the value of a variable can be changed:
>>> x = 3 >>> print (x) 3 >>> >>> x = 5 >>> print (x) 5 >>>
Notice how the first print() function printed the value of 3. We have then changed the value of the variable x to 5. The second print() function printed the value of 5.