Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the global
statement:
def g(n):
global c
c = c + n
This is one of the quirky areas of Python that has never really sat well with me.
More Related Contents:
- Short description of the scoping rules?
- UnboundLocalError on local variable when reassigned after first use
- Local variables in nested functions
- Accessing class variables from a list comprehension in the class definition
- Python 3: UnboundLocalError: local variable referenced before assignment [duplicate]
- Scope of python variable in for loop
- How to access outer class from an inner class?
- Why does this UnboundLocalError occur (closure)? [duplicate]
- How can I change a global variable from within a function?
- How do I pass variables across functions?
- Python: load variables in a dict into namespace
- Python overwriting variables in nested functions [duplicate]
- Python: How can I run eval() in the local scope of a function
- How to create module-wide variables in Python? [duplicate]
- String with ‘f’ prefix in python-3.6
- How to inject variable into scope with a decorator?
- How can a function access its own attributes?
- globals and locals in python exec()
- Does filehandle get closed automatically in Python after it goes out of scope?
- Why is one class variable not defined in list comprehension but another is?
- Getting “global name ‘foo’ is not defined” with Python’s timeit
- How references to variables are resolved in Python [duplicate]
- Nested list comprehension scope
- Global dictionaries don’t need keyword global to modify them? [duplicate]
- Why do I get a `NameError` (or `UnboundLocalError`) from using a named exception after the `except` block?
- UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
- How do the scoping rules work with classes?
- Python global variable scoping
- Why can functions in Python print variables in enclosing scope but cannot use them in assignment? [duplicate]
- Scope of variable within “with” statement?