Unboundlocalerror: Local Variable 'n' Referenced Before Assignment - How Can I Identify And Remove This ? Or Do Debug In This Case?
I have made a proper for loop still But I am getting the below error. UnboundLocalError: local variable 'n' referenced before assignment How do I fix the above error ? import num
Solution 1:
Python variables always work under two kinds of scope - Global and Local. In your case, n=0
is globally defined variable. You cannot directly access it in a function. You can use global
keyword for that purpose.
The following code will work, I've tested it:
import numpy as np
n=0import math
defpolygonPerimeter(x,y):
global n
# np.size(x) returns value 7 for i inrange(np.size(x)-1):
n = n +math.sqrt((x[i]-x[i+1])**2+(y[i]-y[i+1])**2)
P=n
return P
print(polygonPerimeter(np.array([1, 3, 3, 4, 7, 6, 1]), np.array([1, 1, 2, 3, 3, 5, 5])))
You can go by this method, or you can define the variable n=0
locally inside the function. And inside for loop, you have x[i+1]
which will fail for the last element in your numpy array, so I've changed the for loop range to np.size(x)-1
.
Post a Comment for "Unboundlocalerror: Local Variable 'n' Referenced Before Assignment - How Can I Identify And Remove This ? Or Do Debug In This Case?"