Variables store information that can vary through manipulation.
We use variables in our everyday life. Checking your bank balance online, for example; the balance (value) is stored in a variable. The price of an item in a shop is stored in a variable, which is called upon when scanned. All the links on a website are also stored in a variable.
What is a variable?
In programming, a variable is used to store information that we can change and access on the fly. When we declare a new variable, it is stored in a specific spot in the computer’s memory. If we need to retrieve the value that we stored, we can just access it by using the variable’s name.
Variables are used for different reasons, depending on the situation. You can use them to ask the user for information and then store their response, to track the amount of times an event occurs, or even to trigger an event in your program depending on its value.
We will look at these examples in more detail over the next few steps.
How do we declare a variable?
Above we mentioned “declaring a variable”. Before we can declare it, however, we we need to do two things: provide a variable name and decide what information to store.
Naming variables is very important. Having an ambiguous variable name in your program can lead to confusion later on for both you and anyone else reading through it.
It should be short, accurate and descriptive.
We also need to follow some rules for naming variables otherwise we can cause errors in our program. These rules are that variable names must:
- Not contain spaces
- Only contain Letters (A-Z), numbers and underscores (_)
- Start with either a letter or an underscore (variables cannot start with a number)
Here are some examples:
|Good examples of variable names||Bad examples of variable names|
Once we have decided on an appropriate variable name, we can actually declare our variable and store a value. The basic syntax for this is setting our variable name equal to our value:
VariableName = information
For example, let’s say you are a store owner and you currently have 12 apples and 13 oranges in stock. We can store this information in variables like so:
AppleCount = 12 OrangeCount = 13
Once declared, we can then retrieve that value again by calling the variable’s name. In the image below, you can see I am using the
print() function to show the values stored in each of the variables.
print(AppleCount) print(OrangeCount) 12 13
Hopefully, now you understand the basics of declaring variables, why they are used and the general rules that bind them. To reinforce that, let’s do a small exercise on naming variables.
Think of five more examples where we would use variables in the real world and give them each an appropriate variable name. We’ve listed some examples below.
- A user’s bank balance
- The price of a banana
- The age of a user
© Coventry University. CC BY-NC 4.0