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

Source: Internet
Author: User

When we write Python, we sometimes run into situations where we've already defined the variable n outside the function, printed it out inside the function, and then made the variable go up, and then ran into this error:

unboundlocalerror:local variable ' xxx ' referenced before assignment

As shown in the following code slice:

N=0
def func ():
	print n
	n+=1

func ()

This error occurs when the result is run.

This is because after you have modified the variable assignment inside the function, the variable is considered a local variable instead of a global variable by the Python interpreter, and when the program executes to N+=1, because the statement is assigned to n, so n becomes a local variable, then when you execute print N, Because n is not defined as a local variable, this error is thrown naturally.

Consider the following code slice:

N=0
def func ():
	print n

func ()
Because the function does not have another value assigned to n, then print n prints the value of the global variable N.

So how do we get to the operation of printing and then assigning values inside a function? The conclusion is to use the Global keyword to declare that n is a global variable inside the function. The code is as follows:

N=0
def func ():
	global n
	print n
	n+=1

func ()
print n
The results are as follows:

0
1
[finished in 1.0s]

At this point, N becomes a global variable, and there is no problem in modifying the variable inside the function.


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.