Rules for Python local assignment

Source: Internet
Author: User
The code is as follows:


MyVar = 1

Def myfunc ():
MyVar + = 1

MyFunc ()


will prompt for error:

Unboundlocalerror:local variable ' myVar ' referenced before assignment

Python proposes the following hypothesis: If you assign a value to a variable anywhere within the body of the function, Python adds the name to the local namespace.

Statement MyVar + = 1 assigns a value to the name MyVar, the MyVar is part of the local namespace of the function MyFunc, and it does not currently have an associated value, resulting in an error.

WORKAROUND: Use the global statement

The code is as follows:


MyVar = 1

Def myfunc ():
Global MyVar
MyVar + = 1

MyFunc ()

Scope Search Rules:

L: Native (local)

E: Closed (eclosing)

G: Overall (global)

B: Built-in (built-in)

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