Python - Variables
Any value of certain type is stored in the computer's memory for processing. Out of available memory locations, one is randomly allocated for storage. In order to conveniently and repeatedly refer to the stored value, it is given a suitable name. A value is bound to a name by the assignment operator '='.>>> myVar=21
myVar is an identifier (name) referring to integer value 21 (Python treats data value as a value).
However, the same identifier can be used to refer to another value. For example, the below code will assign
myVar as the name of a string value, as shown below.
So, the value being referred can change (or vary), hence it is called a variable. It is important to remember that a variable is a name given to a value, and not to a memory location storing the value.
Variables can be accessed by using their identifier (name) as shown below.>>> myVar="Steve"
One of the important features of Python is that it is a dynamically-typed language. Programming languages such as C, C++, Java, and C# are statically-typed languages. A variable in these languages is a user-friendly name given to a memory location and is intended to store the value of a particular data type.
A variable in Python is not bound permanently to a specific data type. Instead, it only serves as a label to a value of a certain type. Hence, the prior declaration of variable's data type is not possible. In Python, the data assigned to a variable decides its data type and not the other way around.
In the following Python statements, a string value is assigned to a variable 'name'. We can test its type using the
Now the Python interpreter won't object if the same variable is used to store a reference to an integer.>>> name=1234
We can see that the data type of a variable has now been changed to integer. This is why Python is called a dynamically-typed language.
Any suitable identifier can be used as a name of a variable, based on the following rules:
- The name of the variable should start with either an alphabet letter (lower or upper case) or an underscore (_), but it cannot start with a digit.
- More than one alpha-numeric characters or underscores may follow.
- The variable name can consist of alphabet letter(s), number(s) and underscore(s) only. For example,
MyVar123are valid variable names but
1myVarare invalid variable names.
Identifiers in Python are case sensitive. So,
nAmEare treated as different variable names.
Starting the name with a single or double underscore has a special meaning in Python. More about this will be discussed in the chapter on object-oriented Programming.