Common local variable ' x ' referenced before assignment problem

Source: Internet
Author: User
Def fun1 ():
    x = 5
    def fun2 ():
        x *= 2 return
        x return
    fun2 ()

As above code, call FUN1 ()

Run Error: unboundlocalerror:local variable ' x ' referenced before assignment.

This is because for the FUN1 function, x is a local variable, and for the FUN2 function, X is a non global external variable. When the X is modified in fun2, X is treated as a fun2 local variable, the definition of x in FUN1 is masked, and if X is read only in fun2, this error does not occur.

Workaround: Use the nonlocal keyword

Def fun1 ():
    x = 5
    def fun2 ():
        nonlocal x
        x *= 2 return
        x return
    fun2
() fun1 () out[14 ]: 10

With nonlocal x, X is no longer considered an internal variable of fun2 in Fun2 (), and the definition of x in the FUN1 function is not blocked.

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.