The variables and scopes in Python are detailed

Source: Internet
Author: User
Tags define function
Scope Introduction

The scope in Python is divided into 4 cases: l:local, local scope, which is the variable defined in the function;

E:enclosing, the local scope of the nested parent function, which is the local scope of the ancestor function that contains the function, but not the global;

G:globa, a global variable, is a variable defined at the module level, b:built-in, a variable within the system's fixed module, such as int, ByteArray, etc. The order of precedence for a search variable is: scope local > Outer scope > Global >python Built-in scope in the current module, that is, LEGB.

x = Int (2.9) # int built-ing_count = 0 # Globaldef outer (): O_count = 1 # enclosingdef inner (): I_count = 2 # Local

Of course, local and enclosing are relative, and enclosing variables are local to the upper level.

#定义变量a >>> a = 0>>> print a0# define function P () >>> def p (): ... print a ... >>> p () 0# define function P2 () >&G t;> def p2 (): ... print a ... a = 3 ... Print a ... >>> p2 () # Run error, external variable A is referenced first, cannot be re-assigned Traceback (most recent called last): File "
 
  
   
  ", line 1, in
   
   
    
   File "
   
    
     
    ", Line 2, in p2unboundlocalerror:local variable ' a ' referenced before assignment# define function p3 ( ) >>> def p3 (): ... a = 3 # does not refer to direct assignment ... print a ... >>> p3 () 3>>> Print A0 # external variable
   A does not change
     
    
   
 
  

The above is a small series to introduce you to the Python variables and scope of the detailed, if you have any questions please give me a message, small series will promptly reply to everyone. Thank you very much for the support of the Scripting House website!

  • 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.