A deep understanding of Python variables and constants, and a deep understanding of python Variables
A variable is a region in the computer memory. It can store values within the specified range and change the value. For variable-based data types, the interpreter allocates the specified memory and determines what data can be stored in the memory. A constant is a read-only memory area. Once initialized, the constant cannot be changed.
A variable name may consist of letters, numbers, and underscores. It cannot start with a number.
Variable assignment
Variables in Python do not need to be declared. The value assignment operation of variables is the process of variable declaration and definition. Each variable created in the memory contains the variable identifier, name, and data.
A new value assignment in Python creates a new variable. Even if the variable name is the same, the variable IDs are different.
X = 1 # variable assignment defines a variable xprint (id (x) # print the variable x id print (x + 5) # Use the variable print ("=========== gorgeous split line ========= ") x = 2 # define a variable xprint (id (x) # The variable x is a new variable print (x + 5) # The name is the same, however, the new variable x is used.
Continue assignment
x = 'hello python'print(id(x))print(x)
At this time, x becomes a new variable, and the variable type also changes due to the change of the assigned data type.
Here, id () is a Python built-in function. See https://docs.python.org/3/library/functions.html#id
If the variable is not assigned a value, Python considers that the variable does not exist.
Python supports simultaneous assignment of multiple variables.
For example:
A = (, 3) # define a sequence x, y, z = a # assign the sequence values x, y, zprint ("a: % d, B: % d, z: % d "% (x, y, z) # print the result
a, b, c = 1, 2, "john"
Variable Scope
Local variables are variables that can only be used in functions or code blocks. Once a function or code block ends, the lifecycle of local variables also ends. The scope of a local variable is only valid for the function created by the local variable.
For example, if a local variable is defined in fun () in file 1, the local variable can only be accessed by fun (), and fun2 () defined in file 1 cannot be accessed, and cannot be accessed by file 2.
# FileName: file1def fun (): local_var = 100 # define a local variable print (local_var) def fun2 (): zero = local_var-100 # use local variables in fun2 (not allowed) print ("get zero: % d" % zero) fun () # fun2 () print ("local_var-1 = % d" % (local_var-1 )) # use local variables in file 1 (not allowed) ################################# Traceback (most recent call last): # File "E:/python/file1.py", line 10, in <module> # print ("local_var-1 = % d" % (local_var-1) # NameError: name 'local _ var' is not defined ############################### # Traceback (most recent call last): # File "E:/python/file1.py", line 9, in <module> # fun2 () # File "E:/lichenli/python/file1.py", line 6, in fun2 # zero = local_var-100 # NameError: name 'local _ var' is not defined ############################### #
# FileName: file2import file1file1. fun () print (local_var) ######################## running result #100 # Traceback (most recent call last ): # File "E: \ python \ file2.py", line 4, in <module> # print (local_var) # NameError: name 'local _ var' is not defined ########################
The local variables defined in fun () can only be accessed by fun.
Global variables are variables that can be shared by different functions, classes, or files. variables defined outside the function are called global variables. Global variables can be accessed by any function or external file in the file.
# FileName: file1g_num1 = 1 # define the global variable g_num2 = 2 # define the global variable def add_num (): global g_num1 # reference global variable g_num1 = 3 # modify global variable value result = g_num1 + 1 print ("result: % d" % result) def sub_num (): global g_num2 g_num2 = 5 result = g_num2-3 print ("result: % d" % result) add_num () sub_num () print ("g_num1: % d" % g_num1) print ("g_num2: % d" % g_num2) # result: 4 result is a local variable # result: 2 # g_num1: 3 the global variable g_num1 is executed in add_num () function changed # g_num2: 5 the global variable g_num2 is changed when the sub_num () function is executed.
The global reserved word is used to reference global variables. If the global keyword is not applicable, when you assign a value to g_num1 in the function, it is interpreted as defining a local variable g_num1.
# Def other (): result = g_num1 + 2 # apply global variables directly without changing the value of global variables. OK print ("result: % d" % result) other () ######################## result: 3 # result: 4 # result: 2 # g_num1: 3 # g_num2: 5 #######################
# After being added to the sub_num () function definition, def other (): g_num1 = 10 result = g_num1 + 2 print ("result: % d" % result) before the add_num () function call) other () #################### result: 12 # result: 4 # result: 2 # g_num1: 3 # g_num2: 5 ####################
Access global variables in file 2.
# FileName: file2import file1file1. add_num () # g_num1 changed to test = file1.g _ num1 + 1 print ("test: % d" % test)
Avoid using global variables whenever possible. Different modules can freely access global variables, which may lead to unpredictable global variables.
Global variables reduce the universality between functions or modules. Different functions or modules depend on global variables. Similarly, global variables reduce code readability. Readers may not know that a variable called is a global variable.
Constant
A constant is a fixed value that cannot be modified once initialized. For example, numbers "5" and strings "abc" are constants.
Python does not provide reserved words for defining constants. Python is a powerful language. You can define a constant class to implement the functions of constants.
# FileName: const. pyclass _ const: class ConstError (TypeError): pass def _ setattr _ (self, name, value): # if self. _ dict __. has_key (name): 3. if name in self. _ dict __: raise self. constError ("Can't rebind const (% s)" % name) self. _ dict _ [name] = valueimport syssys. modules [_ name _] = _ const ()
#fileName:const_2.pyimport constconst.name='zhangsan'const.name='lisi'###################################Traceback (most recent call last):# File "E:/python/const_2.py", line 4, in <module># const.name='lisi'# File "E:/python\const.py", line 7, in __setattr__# raise self.ConstError("Can't rebind const(%s)"%name)#const._const.ConstError: Can't rebind const(name)##################################
The name variable has been assigned the value "zhangsan" and cannot be assigned any more. Therefore, an exception is thrown. Raise reserved words are used to throw an exception.
The above in-depth understanding of Python variables and constants is all the content shared by the editor. I hope to give you a reference and support for the help house.