Variables
In computer programming, a variable is a named container that holds a value. In Python, you create a variable by assigning a value to it. To assign a value to a variable, you put the variable name followed by an equal sign and the value you want stored. You will then be able to manipulate that value by calling the variable name.
Python variable names can only contain alphanumeric characters and underscores; they cannot begin with a number and are case-sensitive. To enhance code reusability, it is advisable to make sure that a variable name is representative of the value being stored.
Another data type in Python is str, which are strings. In Python, a string is a sequence of characters. For example, ‘blue’ is a string.
In the code example below, we will create a variable favourite_colour that has the value 'blue'. To create a string, you enclose the characters in quotation marks. You can use either single or double quotes.
Creating a variable named favourite_colour with the value 'blue'
To create a variable named favourite_colour that has the value 'blue', enter the below code into a code editor:
favourite_colour = 'blue'
Now that we have created our favourite_colour variable, we can call print on the favourite_colour variable. print is a function in Python that prints the specified message onto the screen. We will explore functions further later in the course.
Printing a variable
To print favourite_colour, enter the code below into a code editor:
print(favourite_colour)
Output
blue
As we assigned the value ‘blue’ to favourite_colour when we printed favourite_colour it returned the string assigned to it.
Try creating some more variables in Python following the guidelines above. For example, try assigning your favourite colour to favourite_colour Or, try creating variables that hold numeric values.