How do you access local variables outside the scope in python?

Global Variables

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.

Let's see an example of how a global variable is created in Python.

Example 1: Create a Global Variable

x = "global"

def foo():
    print("x inside:", x)


foo()
print("x outside:", x)

Output

x inside: global
x outside: global

In the above code, we created x as a global variable and defined a foo() to print the global variable x. Finally, we call the foo() which will print the value of x.

What if you want to change the value of x inside a function?

x = "global"

def foo():
    x = x * 2
    print(x)

foo()

Output

UnboundLocalError: local variable 'x' referenced before assignment

The output shows an error because Python treats x as a local variable and x is also not defined inside foo().

To make this work, we use the global keyword. Visit Python Global Keyword to learn more.


Local Variables

A variable declared inside the function's body or in the local scope is known as a local variable.

Example 2: Accessing local variable outside the scope

def foo():
    y = "local"


foo()
print(y)

Output

NameError: name 'y' is not defined

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.


Let's see an example on how a local variable is created in Python.

Example 3: Create a Local Variable

Normally, we declare a variable inside the function to create a local variable.

def foo():
    y = "local"
    print(y)

foo()

Output

local

Let's take a look at the earlier problem where x was a global variable and we wanted to modify x inside foo().


Global and local variables

Here, we will show how to use global variables and local variables in the same code.

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()

Output

global global 
local

In the above code, we declare x as a global and y as a local variable in the foo(). Then, we use multiplication operator * to modify the global variable x and we print both x and y.

After calling the foo(), the value of x becomes global global because we used the x * 2 to print two times global. After that, we print the value of local variable y i.e local.


Example 5: Global variable and Local variable with same name

x = 5

def foo():
    x = 10
    print("local x:", x)


foo()
print("global x:", x)

Output

local x: 10
global x: 5

In the above code, we used the same name x for both global variable and local variable. We get a different result when we print the same variable because the variable is declared in both scopes, i.e. the local scope inside foo() and global scope outside foo().

When we print the variable inside foo() it outputs local x: 10. This is called the local scope of the variable.

Similarly, when we print the variable outside the foo(), it outputs global x: 5. This is called the global scope of the variable.


Nonlocal Variables

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.

Let's see an example of how a nonlocal variable is used in Python.

We use nonlocal keywords to create nonlocal variables.

Example 6: Create a nonlocal variable

def outer():
    x = "local"

    def inner():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)

    inner()
    print("outer:", x)


outer()

Output

inner: nonlocal
outer: nonlocal

In the above code, there is a nested inner() function. We use nonlocal keywords to create a nonlocal variable. The inner() function is defined in the scope of another function outer().

Note : If we change the value of a nonlocal variable, the changes appear in the local variable.

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.

The following example will underline this point. An attempt to print a local variable outside its scope will raise the NameError exception.

def greet():
    name = 'Steve'
    print('Hello ', name)

Here, name is a local variable for the greet() function and is not accessible outside of it.

>>> greet()                            
Hello Steve
>>> name
Traceback (most recent call last):
File "", line 1, in  name
NameError: name 'name' is not defined

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.

name='John'
def greet():
    print ("Hello ", name)

Now, you can access the global variable name because it has been defined out of a function.

>>> greet()                            
Hello Steve
>>> name
'Steve'

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:

name = 'Steve'
def greet():
    name = 'Bill'
    print('Hello ', name)

Now, changing the value of global variable name inside a function will not affect its global value.

>>> greet()
Hello Bill
>>> name
'Steve'

If you need to access and change the value of the global variable from within a function, this permission is granted by the global keyword.

name = 'Steve'
def greet():
    global name
    name = 'Bill'
    print('Hello ', name)

The above would display the following output in the Python shell.

>>> name                               
'Steve'
>>> greet()                            
Hello Bill
>>> name                               
'Bill'

It is also possible to use a global and local variable with the same name simultaneously. Built-in function globals() returns a dictionary object of all global variables and their respective values. Using the name of the variable as a key, its value can be accessed and modified.

name = 'Steve'
def greet():
    globals()['name'] = 'James'
    name='Steve'
    print ('Hello ', name)

The result of the above code shows a conflict between the global and local variables with the same name and how it is resolved.

>>> name
'Steve'
>>> greet()    
Hello Steve 
>>> name
'James'

Visit Globals and Locals in Python for more information.

How do you access local variables outside a function in Python?

Use the object attribute syntax to access a variable outside of a function. In a function named func , use the syntax func. variable = value to store value in variable as an attribute of func . To access value outside of func , use func() to run func , then use the syntax function_name.

How do you access local variables outside the scope?

Local variables cannot be accessed outside the function declaration. Global variable and local variable can have same name without affecting each other.

How do you use outer scope variables in Python?

You would use global within the scope of a function to indicate that you want to use a variable in the global scope and not in the local scope. In python 3, there is also the nonlocal keyword that allows you to indicate you want to modify a variable in an outer scope that isn't the global/module scope.

How do you access a variable outside a loop in Python?

you have to set the variable a outside the loop. – Murillio4. ... .
a = None or a = "" before with line. – user1935024. ... .
You missed colon in the if line. – volcano. ... .
@Murillio4 Not necessarily; there's only one scope in the posted code, but a is not guaranteed to be set by the code. – chepner. ... .
@mohaned thanks! for your answer..