Variables must start with a letter.
We cannot start variables with a number.
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)
For example if a = 5 and b = 10 we might want to switch them to a = 10 and b = 5
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.