Radhe
Radhe

Reputation: 45

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 numpy as np
n=0
import math
def polygonPerimeter(x,y):
    for i in range(np.size(x)):
        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])))

Upvotes: 1

Views: 613

Answers (1)

amrs-tech
amrs-tech

Reputation: 483

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=0
import math
def polygonPerimeter(x,y):
    global n
    # np.size(x) returns value 7 
    for i in range(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.

Upvotes: 1

Related Questions