Skip to main content

Python: 04 Variables, Data Types and Assignment

Variables are used to store data.

They consist of an identifier or name that is used to reference the contents of the variable 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 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 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 "15" are different data types even though they look the same. One is an integer (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 (floating point / decimal numbers)
  • boolean (true/false)
  • char (single character), Python doesn't have a char type
  • string (text)

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

In programming 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.