Unbondlocalerror:local variable referenced before assigment

Source: Internet
Author: User
<span style= "FONT-SIZE:18PX;" ></span><pre name= "code" class= "python" >y,z = 1,2
def change ():
      y = y+2
      z = z+2 retrun
      y, Z

This code is to change the value of the global variable y,z, it seems that there is no problem, Y,z declared outside the function, the actual operation will be reported unbondlocalerror wrong.

This is because of the Python variable name resolution principle: the LEGB principle. When you use a variable name that is not authenticated in a function, Python searches for 4 scopes [local scope (L), followed by the local scope (E) of def or lambda in the previous layer structure, followed by global scope (G), and finally built-in scope (B)], And stop at the first place where you can find the variable name.

When assigning the variable name ' y ' to ' y+2 ', Python first finds the definition of y in the global variable by looking for y in the ' y+2 ' within the function (that is, the local variable). When Python first looks for the local variable, it finds the variable name y, but y doesn't define it, so even if we define the global variable Y, we still have an error. There are several ways to modify this to avoid this error.

(1) declaring the y,z as a global variable

<span style= "FONT-SIZE:18PX;" >y,z = 1,2
def change ():
      global y,z         #加入这一行
      y = y+2
      z = z+2
      retrun y,z</span>
So there won't be any more errors, when the value is assigned, Python finds the variable name y, but y is a global variable, not a local variable, so Python does not find the definition of Y in the function, so it looks for y from the global variable, which gives us the results we want.

(2) Put the definition of y,z in the function

def change ():
      y,z = 1,2
      y = y+2
      z = z+2
      retrun y,z

Python finds the definition of y,z within a function, and there is no error. But it doesn't change the value of the y,z, and when the function is finished, the Y,z object does not exist.






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.