Variables (names)

https://docs.python.org/3/library/index.html

INTRODUCTION

Names (or variables) refer to objects. Names are introduced by name binding operations.

Variables could be thought of as a sticky label you can place on a value.


# The following constructs bind names.

name1 = expression   # assignements
name2 = name1     # the same value with two 'labels'

def function_name(parameter_name):   # function definitions
    pass

class ClassName:   # class definitions
    pass

import module_name   # import statements

for item_name in sequence:
    pass

with expression as context_name:   # with statements
    pass

try:
    statements
except exception_name as exception_instance_name:
    statements

del some_name   # unbinding names

>>> X
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'X' is not defined
>>> X = 11           # creating X
>>> X                # checking a value
11
>>> del X     # destroying the variable X (the value 11 can survive)
>>>

REFERENCE COUNTING


import sys

word1 = "qwertyuiop"
sys.getrefcount(word1)   # 2
word2 = word1
sys.getrefcount(word1)   # 3
sys.getrefcount(1)   # 149
word2 = 2021

#  name
# +-----------+
# | "word1"   |         string (value)
# +-----------+        +--------------+
# | reference |-------o| "qwertyuiop" |
# +-----------+        +--------------+
#                      | refs counter |
#  name                +--------------+  integer (value)
# +-----------+             o           +--------------+
# | "word2"   |    (1)      |           | 2021         |
# +-----------+-------------+           +--------------+
# | reference |------------------------o| refs counter |
# +-----------+    (2)                  +--------------+

PYTHON KEYWORDS

https://docs.python.org/3/library/keyword.html

'Keywords' cannot be used as ordinary identifiers.


>>> help()   # Py2 and Py3
help> keywords
...
help> quit
>>>

import keyword   # Py3

keyword.kwlist   # sequence containing all the keywords
keyword.iskeyword("True")   # True
keyword.iskeyword("self")   # False
keyword.iskeyword("max")   # False

EXERCISES

(1) Find all the keywords of the language.

(2) Check reference counters for several numbers and strings.