Python's unboundlocalerror:local variable ' xxx ' referenced before assignment

Source: Internet
Author: User

First, meaning

The local variable XXX reference was not defined before.

ii. Causes of Errors

Is that Python does not have a variable declaration, so it finds the scope of the variable by a simple rule: if there is a variable assignment inside a function, the variable is considered local, so if the value of the modified variable becomes a local variable.

Iii. The scene that produced this error
Python code:
val=9
def test (flag):
If flag:
val = 1
Else
print ' Fuck '
Return Val

Test (0)
Error tip: unboundlocalerror:local variable ' Val' Referenced before assignment

Workaround:Using the Global keyword to illustrate that the variable is a global variable
Python code:
val=9
def test (flag):
Global Val
If flag:
val = 1
Else
print ' Test '
Return Val

Test (0) Reference: http://www.uplook.cn/biancheng/107/1078875/reprinted from: http://blog.csdn.net/joeblackzqq/article/details/35278665

Python's unboundlocalerror:local variable ' xxx ' referenced before assignment

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.