Unboundlocalerror:local variable ' XXX ' referenced before assignment

Source: Internet
Author: User

The problem is very awkward, the outside definition of a variable xxx, and then in a Python function to reference this variable, and change its value, the results of the error local variable ' xxx ' referenced before assignment, the code is as follows:

View plain Copy to clipboard print?           xxx = def printfilename (strFileName): if xxx = =: print strFileName xxx = printfilename ("file")

The wrong meaning is that the variable XXX is not defined before the reference, which is not defined above. But then I took xxx = 24 after the sentence was removed, then no problem, and then think of Python in a global keyword is used to refer to the overall variables, try it, sure enough:

View plain Copy to clipboard print? xxx = def printfilename (strFileName): global xxx if xxx = =: p rint strFileName xxx = printfilename ("file")

A variable that originally had the same name in the Python function as the global if you have a value that modifies a variable, it becomes a local variable, and a reference to that variable will naturally occur before you modify it, and if you decide that you want to refer to the global variable and you want to modify it, you must add the Global keyword.

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.