Local variable 'xxx' referenced before assignment

Source: Internet
Author: User

This problem is very difficult. A variable XXX is defined outside, and then this variable is referenced in a function in Python and its value is changed, the error "local variable 'xxx' referenced before assignment" is returned,CodeAs follows:

Xxx = 23 <br/> def printfilename (strfilename): <br/> If xxx = 23: <br/> Print strfilename <br/> xxx = 24 </P> <p> printfilename ("file ")

The error means that the variable XXX has not been defined before reference. Isn't it defined above? However, after I removed xxx = 24, it was okay. Later I remembered that there was a global keyword in Python that was used to reference global variables. I tried it and it was okay:

Xxx = 23 <br/> def printfilename (strfilename): <br/> global XXX <br/> If xxx = 23: <br/> Print strfilename <br/> xxx = 24 </P> <p> printfilename ("file ")

In Python functions, if you change the value of a variable to a local variable, before modification, the reference to this variable will naturally lead to the failure to define such an error. If you are sure to reference the global variable and want to modify it, you must add the Global keyword.

[End]

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.