Python variables and constants

Source: Internet
Author: User
Tags variable scope

A variable is an area of computer memory in which variables can store values within a specified range, and values can be changed. Based on the data type of the variable, the interpreter allocates the specified memory and determines what data can be stored in memory. Constants are a read-only area of memory that cannot be changed once they are initialized.

Variable name letters, numbers, underscores, can not start with a number, the previous article said not to repeat.

Assigning values to variables

Variables in Python do not need to be declared, and the assignment of variables is the process of declaring and defining variables. Each variable is created in-memory to include the identity, name, and data of the variable.

A new assignment in Python will create a new variable. Variables are identified and differ, even if the names of the variables are the same.

 x = 1 #   variable assignment defines a variable x  print  (ID (x))  print the identity of the variable x  print  (x+5)  use variables  print  ( ========= Gorgeous split line =========   ) x  = 2 #   print  (ID (x)) #   print  (x+5) #   The name is the same, but the new variable x  
is used

Continue to assign value

' Hello python ' Print (ID (x)) Print (x)

At this point, X becomes a new variable, and the variable type is changed by the data type of the assigned value.

Here, the ID () is a python built-in function. See also: Https://docs.python.org/3/library/functions.html#id

If the variable is not assigned a value, Python will assume that the variable does not exist.

Python supports simultaneous assignment of multiple variables.

For example:

# defines a sequence of x, y, z = a    # to assign the value of the sequence to the values of ×, y, zprint("A:%d, B:%d, z:%d " # Print Results

" John "

Variable scope

A local variable is a variable that can only be used within a function or code block, and once the function or block of code has ended, the life cycle of the local variable will end. The scope of a local variable is valid only within the function that the local variable is created in.

For example, a local variable is defined in fun () in file 1, the local variable can only be accessed by fun (), the fun2 () defined in file 1 cannot be accessed, and cannot be accessed by file 2.

#Filename:file1defFun (): Local_var= 100#define a local variable    Print(Local_var)deffun2 (): Zero= local_var-100#use local variables in fun2 (not possible)    Print("get zero:%d"%zero) fun ()#fun2 ()Print("local_var-1 =%d"% (local_var-1))#using local variables in file 1 (not allowed)#################################Traceback (most recent):#File "e:/python/file1.py", line ten, in <module>#print ("local_var-1 =%d"% (local_var-1))#nameerror:name ' Local_var ' is not defined#################################Traceback (most recent):#File "e:/python/file1.py", line 9, <module>#fun2 ()#File "e:/lichenli/python/file1.py", line 6, in Fun2#zero = local_var-100#nameerror:name ' Local_var ' is not defined################################

#Filename:file2ImportFile1file1.fun ()Print(Local_var)#########################Run Results# -#Traceback (most recent):#File "E:\python\file2.py", line 4, <module>#print (Local_var)#nameerror:name ' Local_var ' is not defined########################

The local variables defined in fun () are only fun to access.

Global variables are variables that can be shared by different functions, classes, or files, and variables defined outside of a function are called global variables. Global variables can be accessed by any function and external file within the file.

#Filename:file1G_NUM1 = 1#Defining global VariablesG_NUM2 = 2#Defining global Variablesdefadd_num ():GlobalG_num1#referencing global variablesG_NUM1 = 3#Modifying the value of a global variableresult = G_num1 + 1Print("Result:%d"%result)defsub_num ():Globalg_num2 g_num2= 5result= G_num2-3Print("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 global variable G_NUM1 is changed when executing the Add_num () function#g_num2:5 global variable g_num2 is changed when executing the Sub_num () function

The global reserved word is used to refer to globals, and if the global keyword is not applied, the G_NUM1 assignment in the function will be interpreted as defining a local variable G_NUM1.

#after adding to the sub_num () function definition, the Add_num () function is called beforedefOther (): Result= G_num1 + 2#Direct Application global variable does not change the value of the global variable OK    Print("Result:%d"%result) Other ()########################Result:3#Result:4#Result:2#G_num1:3#G_num2:5#######################

#after adding to the sub_num () function definition, the Add_num () function is called beforedefOther (): G_num1= 10result= G_num1 + 2Print("Result:%d"%result) Other ()#####################Result:12#Result:4#Result:2#G_num1:3#G_num2:5####################

Access global variables in file 2.

# Filename:file2 Import  #g_num1 changed test = file1.g_num1 + 1print("test:%d"% Test

You should try to avoid using global variables. Different modules are free to access global variables, which can lead to unpredictable global variables.

Global variables reduce the commonality between functions or modules, and different functions or modules depend on global variables. Similarly, global variables reduce the readability of the code, and the reader may not know that a variable being called is a global variable.

Constant

A constant is a fixed value that cannot be modified once it is initialized. For example: the number "5", the string "ABC" are constants.

There are no reserved words for defining constants in Python. Python is a powerful language that can define a constant class to implement the function of a constant.

#fileName:const.pyclass_const:classConsterror (TypeError):Pass    def __setattr__(self,name,value):#if Self.__dict__.has_key (name): Has_key discarded after 3.x        ifNameinchSelf.__dict__:            RaiseSelf. Consterror ("Can ' t rebind const (%s)"%name) self.__dict__[Name] =valueImportsyssys.modules[__name__] = _const ()

#fileName:const_2.pyImportConstconst.name='Zhangsan'Const.name='Lisi'###################################Traceback (most recent):#File "e:/python/const_2.py", line 4, <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)##################################

Name this variable has been assigned the value "Zhangsan" cannot continue to be assigned, so throws an exception. Raise reserved words are used to throw exceptions.

Python variables and constants

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.