local variable 'p' referenced before assignment

David bouncingcats at gmail.com
Sun Sep 8 06:23:51 EDT 2019


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

https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

" 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.



More information about the Python-list mailing list