Python: Use of function variables

Source: Internet
Author: User

1. The upper function cannot directly use the variables of its nested function;

def func1 (x, y):     = x + y    def  Func2 ():        = 3    + =    mreturn  Zprint (Func1 (1, 2))#  error: Name ' m ' is not defined

2. Variables in the upper function can be used directly within their nested functions:

def func1 (x, y):     = x + y    def  Func2 ():        = 3 + z        return  m      return  func2 ()print(func1 (1, 2))#  output: 6

3. In nested functions, the upper function variable cannot be used, and its own variable has the same name as the upper layer variable:

def func1 (x, y):     = x + y    def  Func2 ():        # m=3 + z:z is the upper function variable        m = 3 + z          # z=m * * 2:z is a variable of the FUNC2 () function itself        z = m * * 2        return     zreturn  Func2 ()print(func1 (1, 2))#  error: local variable ' z ' referenced before assignment 

# declare the variable in advance to be a non-local variable (the system automatically looks for the variable from the upper function): nonlocal Z

# Variables in code z are all variables of the func1 () function

    • def func1 (x, y):     = x + y    def  Func2 ():        nonlocal z        = 3 + z        + = m         return Z     return Func2 () Print (Func1 (1, 2)) # Output: 9

4. The formal parameter of the upper function (x, y) can be used directly in its nested function;

def func1 (x, y):     def Func2 ():         = 3 + x        = m + y        return  z    return  func2 () Print (Func1 (1, 2)) # Output: 6

5. The formal parameter of the upper function (x, y) can be the formal parameter of its nested function: The name of the formal parameter must be the same

def func1 (x, y):     def Func2 (x, y):         = 3 + x        = m + y        return  z    return  func2 (x, y) C15>print(func1 (1, 2))#  output: 6

Python: Use of function variables

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.