A variable declared inside the function's body or in the local scope is known as a local variable.,In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.,The output shows an error because we are trying to access a local variable y in a global scope whereas the local variable only works inside foo() or local scope.,Nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope.
Example 1: Create a Global Variable
x = "global" def foo(): print("x inside:", x) foo() print("x outside:", x)
x inside: global x outside: global
What if you want to change the value of x inside a function?
x = "global" def foo(): x = x * 2 print(x) foo()
Normally, we declare a variable inside the function to create a local variable.
def foo(): y = "local" print(y) foo()
Example 4: Using Global and Local variables in the same code
x = "global " def foo(): global x y = "local" x = x * 2 print(x) print(y) foo()
Last Updated : 15 Jul, 2022
I love Geeksforgeeks
I love Geeksforgeeks
NameError: name 's' is not defined
Inside Function I love Geeksforgeeks Outside Function I love Geeksforgeeks
Me too. I love Geeksforgeeks
Python is great!GFG Look for Geeksforgeeks Python Section Look for Geeksforgeeks Python Section
By Bernd Klein. Last modified: 29 Jun 2022.
def f(): print(s) s = "I love Paris in the summer!" f()
I love Paris in the summer!
def f(): s = "I love London!" print(s) s = "I love Paris!" f() print(s)
I love London! I love Paris!
def f(): print(s) s = "I love London!" print(s) s = "I love Paris!" f()
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-3-d7a23bc83c27> in <module> 5 6 s = "I love Paris!" ----> 7 f() <ipython-input-3-d7a23bc83c27> in f() 1 def f(): ----> 2 print(s) 3 s = "I love London!" 4 print(s) 5 UnboundLocalError: local variable 's' referenced before assignment
In general, a variable that is defined in a block is available in that block only. It is not accessible outside the block. Such a variable is called a local variable. Formal argument identifiers also behave as local variables. , Any variable present outside any function block is called a global variable. Its value is accessible from inside any function. In the following example, the name variable is initialized before the function definition. Hence, it is a global variable. , However, if we assign another value to a globally declared variable inside the function, a new local variable is created in the function's namespace. This assignment will not alter the value of the global variable. For example: , Here, name is a local variable for the greet() function and is not accessible outside of it.
def greet(): name = 'Steve' print('Hello ', name)
>>> greet() Hello Steve >>> name Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> name NameError: name 'name' is not defined
name = 'John' def greet(): print("Hello ", name)
>>> greet() Hello Steve >>> name 'Steve'
name = 'Steve' def greet(): name = 'Bill' print('Hello ', name)
>>> greet() Hello Bill >>> name 'Steve'
Using parameters and return (recommended)
def other_function(parameter): return parameter + 5 def main_function(): x = 10 print(x) x = other_function(x) print(x)
When you run
main_function, you'll get the following output
>>> 10 >>> 15
Using globals (never do this)
x = 0 # The initial value of x, with global scope def other_function(): global x x = x + 5 def main_function(): print(x) # Just printing - no need to declare global yet global x # So we can change the global x x = 10 print(x) other_function() print(x)
Simply declare your variable outside any function:
globalValue = 1 def f(x): print(globalValue + x)
If you need to assign to the global from within the function, use the
def f(x): global globalValue print(globalValue + x) globalValue += 1
If you need access to the internal states of a function, you're possibly better off using a class. You can make a class instance behave like a function by making it a callable, which is done by defining
class StatefulFunction(object): def __init__(self): self.public_value = 'foo' def __call__(self): return self.public_value >> f = StatefulFunction() >> f() `foo` >> f.public_value = 'bar' >> f() `bar`
Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:
def foo(): global bar bar = 32
You could use module scope. Say you have a module called
f_value = 'foo' def f(): return f_value
f_value is a module attribute that can be modified by any other module that imports it. As modules are singletons, any change to
utils from one module will be accessible to all other modules that have it imported:
>> import utils >> utils.f() 'foo' >> utils.f_value = 'bar' >> utils.f() 'bar'
Note that you can import the function by name:
>> import utils >> from utils import f >> utils.f_value = 'bar' >> f() 'bar'
In Python, variables that are only referenced inside a function are implicitly global. 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.,This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope:,Guido van Rossum recommends avoiding all uses of from <module> import ..., and placing all code inside functions. Initializations of global variables and class variables should use constants or built-in functions only. This means everything from an imported module is referenced as <module>.<name>.,Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use None as the default value and inside the function, check if the parameter is None and create a new list/dictionary/whatever if it is. For example, don’t write:
>>> x = 10 >>> def bar(): ...print(x) >>> bar() 10
>>> x = 10 >>> def foo(): ...print(x) ...x += 1
>>> foo() Traceback(most recent call last): ... UnboundLocalError: local variable 'x' referenced before assignment
>>> x = 10 >>> def foobar(): ...global x ...print(x) ...x += 1 >>> foobar() 10
>>> print(x) 11
>>> def foo(): ...x = 10 ...def bar(): ...nonlocal x ...print(x) ...x += 1 ...bar() ...print(x) >>> foo() 10 11
Next, we assign the value 2 to x. The name x is local to our function. So, when we change the value of x in the function, the x defined in the main block remains unaffected. , When you declare variables inside a function definition, they are not related in any way to other variables with the same names used outside the function i.e. variable names are local to the function. This is called the scope of the variable. All variables have the scope of the block they are declared in starting from the point of definition of the name. , The global statement is used to decare that x is a global variable - hence, when we assign a value to x inside the function, that change is reflected when we use the value of x in the main block. , If you want to assign a value to a name defined outside the function, then you have to tell Python that the name is not local, but it is global. We do this using the global statement. It is impossible to assign a value to a variable defined outside a function without the global statement.
Example 7.3. Using Local Variables
#!/usr/bin/python # Filename: func_local.py def func(x): print 'x is', x x = 2 print 'Changed local x to', x x = 50 func(x) print 'x is still', x
$ python func_local.py x is 50 Changed local x to 2 x is still 50
Example 7.4. Using the global statement
#!/usr/bin/python # Filename: func_global.py def func(): global x print 'x is', x x = 2 print 'Changed global x to', x x = 50 func() print 'Value of x is', x
$ python func_global.py x is 50 Changed global x to 2 Value of x is 2