Variables and datatypes

When a program runs it will use, modify and store data. For example a calculator willl allow the user to enter a number, perform a calculation and then display the result. This data is stored in primary memory. A single block of data is known as a variable. Variables act a bit like algebra where each letter will represent a different value. When a value is placed into a variable it is said to be "assigned" to the variable.

Variable - A named reference to a block of data which can store values and be used in further calculations

Assignment - The process of setting a peice of data into a variable. Data is always copied from right to left.

The source code below shows some example variable assignments. The equals sign is used to represent assignment. It is always important to remember that values always go from right to left. Any code on the right hand side will always be run before the value is assigned.


x = 5 
y = 2
z = 10 + 5 # stores the value 15 into z
p = x * y # will store the value 10 into z
					
					

Variables have three main parts. A name, a value and a data type. There are many different data types such as date, text or real values. It is important not to mix up data types, like adding text to a number, as the results may not be accurate. Adding text to a number would cause an error. In order to get around this you may need to cast a variable into a different data type. The source code below demonstrates this


x = 1 + "hello" # causes an error as "hello is text"
x = 1 + "1" # still causes an error as "1" is treated as text!
x = 1 + int("1") # this works as 1 has been cast to a integer (a number)
x = 1 + int("hello") # causes an error as "hello" can not be converted into a number.
					
					

Data type - The type of data which can be stored in a variable. Once set a variable can only store values which have that data type.

Casting - The process of converting a variable from one data type to another. Errors occur if what you cast is not valid.