4 Variables, Data Types and Assignment


Variables[2] are used to store data[6].

They consist of an identifier or name that is used to reference the contents of the variable[3] throughout the program.

They are used to store data (content).

A variable must be created and have data assigned to it before it can be used in a program.

Python[7] is known as a dynamically-typed language. This means that when you create a variable you don’t have to state what sort of data will be stored in it and you can change what sort of data it contains at anytime.

This makes creating variables[2] easy but means that we have to by careful to make sure that we keep the same type of data in a variable.

For example the number 15 and the string[8] “15” are different data types even though they look the same. One is an integer[9] (15) and the other is a string (“15”).

Imagine if you had a number 15 and a string “a” and you typed 15 + “a”. You can’t add these two values together.

Common data types are:

  • integer (whole numbers)
  • float[10] (floating point / decimal numbers)
  • boolean[4] (true/false)
  • char (single character[5]), Python doesn’t have a char type
  • string (text)

Variable[3] names must start with a letter and can contain letters, numbers and underscore _ .

In programming[1] we use the = to mean assignment which will store the data on the right of the = in the variable listed to its left.

Here are some examples:

age = 15
first_name = "Bob"
year_of_birth = 2000
cost = 4.50
number_purchased = 10
total_cost = cost * number_purchased

Whatever is written to the right of the = symbol will be carried out and the result stored in the variable on the left of the =.

In the final line above this will get the value stored in the cost variable and multiply it with the value in the number_purchased variable and then assign it to the total_cost variable.

Terms definitions
1. programming. The process of writing a programme
2. Variables. “Containers” used to label and store data in memory. The data can then be used throughout a program: * Integer variables use only numbers and so can be used for calculations * String variables are sequences of code that may contain numbers, letters, and other characters, and so cannot be used for calculations.
3. variable. A placeholder for a piece of information that can change.
4. boolean. A data type that can store two values, true/false, yes/no, 0/1, on/off, etc.
5. character. A data type used to store a single character. Often enclosed in ‘a’