Python Variables

A variable is nothing more than a name given to a particular area in memory that stores a value created by a Python program. Variable names in Python can contain letters, numbers and underscores, but must start with either a letter or underscore. Unlike some languages, for example C#, Python is a loosely typed language, which means that when a variable is declared, a datatype does not have to be assigned. A variable is automatically converted to the correct datatype depending on the value that is assigned to it.

When creating a variable, it takes the following format. The equals sign between the variable name and value is known as an assignment operator and will be discussed further in the next section on operators.

variable_name = value

The value being assigned to a variable could potentially be the value of another variable.

variable_name2 = variable_name1

Note that in this case a copy of the value in ‘variable_name1’ is assigned to ‘variable_name2’. There is no link made between the two, so when the value of one of the variables changes it is independent of the other.

Below are some example variables, the last of which is a boolean variable, that can either be ‘True’ or ‘False’.

# Integer variable.
example_integer = 5

# Floating point or decimal number variable.
example_float = 5.0

# String variable.
example_string = "This is a string"

# Boolean variable.
example_boolean = True

One final thing to note is that variable names must not be the same as reserved words in the Python programming language. Reserved words have a specific meaning and cannot be used for anything else. They are shown in blue on the preceding and following pages.