Variables¶
Definition¶
Variables are areas in RAM where we can store one value. Each variable has a variable name (also known as an identifier). We use the variable name to refer to the value stored in the variable.
Note
A value could be a string, integer, floating point number or Boolean. For example, 'Adam'
, 5
, 11.89
or True
.
Easy example¶
name = 'Smith'
There is no output but “Smith” is stored in RAM. We say that "Smith"
is assigned to the variable name
.
Syntax¶
variableName = value
Examples¶
Example 1 - A variable to store a number¶
age = 15
Assigns 15
to age
. The value 15
is stored in RAM.
Example 2 - A variable to store a name¶
playerName = 'Adam'
Assigns 'Adam'
to playerName. The value 'Adam'
is stored in RAM.
Example 3 - A variable to store the current state of a game¶
gameOver = False
Assigns False
to gameOver. The value False
is stored in RAM
Example 4 - A variable to store the result of a calculation¶
base = 20
height = 15
triangleArea = (1/2) * base * height
print(triangleArea)
150.0
Key points¶
Note
The =
symbol is known as the assignment operator. This is not the same as an equals symbol.
Warning
The value on the right of the =
gets stored in the variable on the left. So 'Smith' = name
will not work. The error that will appear is SyntaxError: can't assign to literal
Danger
You cannot use spaces in a variable name. For example, player name = 'Smith'
will not work. The error that will appear is SyntaxError: invalid syntax
Hint
You can use two words for a variable name joing them together. For example, playerName = 'Smith'
This is known as camel case.
Note
Python doesn’t have constants. For constants, simply make a variable and don’t change it!