Lesson 3: Variables
Introduction
We use variables to assign values which we want to use later in our code, usually repeatedly.
In computer programming, a variable is a reference to a piece of data (i.e. a value). Variables are used in a way that is similar to the way x and y are used in algebra.
Examples:
x = 10 y = -3 firstName = "John"
The variable name is always on the left of the equals sign. The value is always on the right of the equals sign.
Variables can be re-used. You can assign a value to a variable, and then replace it with another value.
For example:
# This will print 20 to the screen x = 20 print(x)
# This will print 10 to the screen x = 10 print(x)
Variable Types
Variables can be used to store numbers (known as integers or floats) or text (known as strings) or true/false values (known as boolean values). Integers, floats, strings and booleans are known as types.
In Python, you do not need to specify the type of variable when you create it. You can create a variable as one type, and then overwrite it with another type value.
For example, the following code is permitted and will not cause an error:
# This will print 25 to the screen myVariable = 25 print(myVariable)
# This will print Hello to the screen myVariable = "Hello" print(myVariable)
Casting
To specify a variable type, use casting. Casting can convert one type to another type.
# This will cast the variable as an integer and print 10 to the screen myNumber = int(10) print(myNumber)
# This will cast the variable as a string and print "10" to the screen myNumber = str(10) print(myNumber)
The important thing to note in the above examples is that the second code snippet prints "10". The quotation marks means it is a string.
A typical reason for casting is to combine a string and an integer. This is known as concatenation.
# This will cause a casting error - TypeError: cannot concatenate 'str' and 'int' objects myNumber = 20 print("My favourite number is " + myNumber)
# To solve this, cast myNumber to a string myNumber = str(20) print("My favourite number is " + myNumber)
Case Sensitivity
Variable names are case-sensitive. The following variables are not the same even though they all have the same value. Three variables will be created:
myApp = "TikTok" myapp = "TikTok" MyApp = "TikTok"
The following example will cause an error:
myFavouriteSimpson = "Homer" print(Myfavouritesimpson)
Combining Variables
Variables can be combined to provide values for other variables. For example, the following block (i.e. lines) of code contains three variables: tableCount, legsPertable and totalLegCount. The first two variables are used to calculate the value for the third variable:
tableCount = 3 legsPertable = 4 totalLegCount = tableCount * legsPertable print("The total number of legs is: ", totalLegCount)
What do you think will be printed when this code is run?
Try It Out!
Create A Variable
Try It
Create a variable named myNumber and give it a value of 6.