Variables must start with a letter.
For example a variable to store a person’s first name could be first_name
We cannot start variables with a number.
In programming the = symbol is known as the assignment operator. It is used to assign (store) data in a variable.
We assign what is on the right of the = to the variable on the left of the =.
To the right of the = we can carry out the processing to modify the data to store in the variable.
Below are five examples of variables that have data stored in them.
first_name = "Lenny" surname = "Learner" age = 15 account_balance = 3.50 is_gamer = True
We can change the data stored in a variable as shown below.
Lines 2 and 4 are to show the output that has changed.
price = 3.5 print("Price before: ", price) price = 4 print("Price after: ", price)
Another thing that you might want to do with variables is switch the values between two variables.
For example if a = 5 and b = 10 we might want to switch them to a = 10 and b = 5
To achieve this we need to create a placeholder variable. If we don’t do this and use the code below we will lose the contents of one vairable.
a = 5 b = 10 print("A: ", a, "B: ", b) a = b b = a print("A: ", a, "B: ", b)
The code above will print
A: 5 B: 10 A: 10 B: 10
This isn’t what we want.
The code below uses a placeholder value to temporarily hold the value of the variable that we are overwriting first.
a = 5 b = 10 print("A: ", a, "B: ", b) temp = a a = b b = temp print("A: ", a, "B: ", b)
Variables are really important and useful and will be used thoroughly throughout your programming journey.