[Timlinux] The role of Python nonlocal and global

Source: Internet
Author: User

1. Execute code

The following examples are executed by executing the following code, which requires the following execution code to be placed behind the instance code.

A = Outer_func ()
= Outer_func ()
Print ("Call B ()") b () b () b ()
2. nonlocal not used
def Outer_func ():     = 3    def  Inner_func ():        + = 1        print("count" , Count)     return Inner_func # output>>> #     Count + = 1#unboundlocalerror:local variable ' count ' referenced before assignment 
3. Using nonlocal
defOuter_func (): Count= 3defInner_func (): nonlocal count Count+ = 1Print("Count", Count)returnInner_func#output>>>#Call A ()#Count 4#Count 5#Count 6#Call B ()#Count 4#Count 5#Count 6
4. Using Global (Error)
def Outer_func ():     = 3    def  Inner_func ():        Global  count        + = 1        print( " Count " , Count)     return Inner_func # output>>> #      Count + = 1#  nameerror:name ' count ' is not defined

5. Using Global (Success)
Count = 3defOuter_func ():defInner_func ():GlobalCount Count+ = 1Print("Count", Count)returnInner_func#output>>>#Call A ()#Count 4#Count 5#Count 6#Call B ()#Count 7#Count 8#Count 9

[Timlinux] The role of Python nonlocal and global

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.