[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

local variable 'p' referenced before assignment

On Sun, 8 Sep 2019 at 19:55, Pankaj Jangid <pankaj.jangid at gmail.com> wrote:
> Why this code is giving local variable access error when I am accessing
> a global variable?

> p = 0
> def visit():
>    m = 1
>    if m > p:
>        p = m


" If a variable is assigned a value anywhere within the function?s body,
it?s assumed to be a local unless explicitly declared as global."

So to avoid causing this error, inside your function you must
explicitly declare p as global before you try to assign to it.

Inside your function, you need a statement:
global p
before you try to assign to p.