Re: local variable 'p' referenced before assignment
David writes: > 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." > Coming with a baggage of other languages. :-) I should have searched it. Thanks a lot for sharing this. Regards. -- Pankaj Jangid -- https://mail.python.org/mailman/listinfo/python-list
Re: local variable 'p' referenced before assignment
On Sun, 8 Sep 2019 at 19:55, Pankaj Jangid 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. -- https://mail.python.org/mailman/listinfo/python-list
local variable 'p' referenced before assignment
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 visit() print(p) If I change the variable assignment inside the function to q = m then it works fine. Like this p = 0 def visit(): m = 1 if m > p: q = m# Changed 'p' to 'q' visit() print(p) -- Pankaj Jangid -- https://mail.python.org/mailman/listinfo/python-list