gunmin Lee
gunmin Lee

Reputation: 31

Python Global variable gives NameError

My code:

def draw_lines(img, lines, color, thickness) :
    x_right = []
    y_right = []
    x_left = []
    y_left = []
    numItr = 1

    for line in lines :
        for x1,y1,x2,y2 in lines :
        global numItr
        numItr += 1

And this is error:

NameError: name 'numItr' is not defined    

Upvotes: 1

Views: 870

Answers (2)

Jacques de Hooge
Jacques de Hooge

Reputation: 6990

No need to use global or nonlocal here, just:

def draw_lines(img, lines, color, thickness) :
    x_right = []
    y_right = []
    x_left = []
    y_left = []
    numItr = 1

    for line in lines :
        for x1,y1,x2,y2 in lines :
            numItr += 1

You only need global if you want to write to a module level variable. And you only need nonlocal if you want to write to a variable that's local to a lexically enclosing function, e.g. the function in which you define your function.

Both cases don't apply to your code, you're just staying inside one function.

In your case the interpreter complains, while by using the word global you indicate that there is a module level variable called numItr, which there isn't.

Upvotes: 1

sahama
sahama

Reputation: 679

Perhaps your problem is that numItr not declared before draw_lines function. look at this https://stackoverflow.com/a/423596/6876911

Upvotes: 0

Related Questions