Variables in Python do not require variable type declaration (since Python is a language with dynamic typing) and they are references to a memory area. Variable naming rules:
Name of variable can consist only of letters, digits and an underscore
Name cannot start with a digit
Name cannot contain special characters @, $, %
An example of creating variables in Python:
In : a = 3 In : b = 'Hello' In : c, d = 9, 'Test' In : print(a,b,c,d) 3 Hello 9 Test
Note that Python does not need to specify that “a” is a number, and “b” is a string.
Variables are references to memory area. This can be demonstrated by using
id() which shows object ID:
In : a = b = c = 33 In : id(a) Out: 31671480 In : id(b) Out: 31671480 In : id(c) Out: 31671480
In this example you can see that all three names refer to the same identifier, so it is the same object to which three references “a”, “b” and “c” point. Python numbers has one feature that can be slightly misleading: numbers from -5 to 256 are pre-created and stored in an array (list). Therefore, when you create a number from this range you actually create a reference to number in generated array.
This feature is specific to implementation of CPython which is discussed in book
This can be verified as follows:
In : a = 3 In : b = 3 In : id(a) Out: 4400936168 In : id(b) Out: 4400936168 In : id(3) Out: 4400936168
b and number
3 have identical identifiers.
They are all references to an existing number in the list.
If you do the same with number more than 256, all identifiers will be different:
In : a = 500 In : b = 500 In : id(a) Out: 140239990503056 In : id(b) Out: 140239990503032 In : id(500) Out: 140239990502960
However, if you assign variables to each other, identifiers are all the same
(in this version
c are referring to the same object):
In : a = b = c = 500 In : id(a) Out: 140239990503080 In : id(b) Out: 140239990503080 In : id(c) Out: 140239990503080
Variable names should not overlap with names of operators and modules or other reserved words. Python has recommendations for naming functions, classes and variables:
variable names are usually written in lowercase or in uppercase (e.g., DB_NAME, db_name)
function names are written in lowercase, with underline between words (for example get_names)
class names are given with capital letters without spaces, it is called CamelCase (for example, CiscoSwitch)