Uncategorized

Python Global, Local and Nonlocal variables

Python Global, Local and Nonlocal variables

In this article, you’ll learn about Python Global Variable, Local Variable, Nonlocal Variable and where to use them.

Global Variables

In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.

Let’s see an example on 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)
Run

When we run the code, the will output be:

x inside : global
x outside: global

In 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 value of x inside a function?

x=“global”
def foo():
x = x * 2
print(x)
foo()
Run

When we run the code, the will output be:

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 global keyword, to learn more visit Python Global Keyword.


Local Variables

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

Example 2: Accessing local variable outside the scope

deffoo():
y = “local”
foo()
print(y)
Run

When we run the code, the will output be:

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.

deffoo():
y = “local”
print(y)
foo()
Run

When we run the code, it will output:

local

Let’s take a look to 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 same code

x=“global”
def foo():
global x
y = “local”
x = x * 2
print(x)
print(y)
foo()
Run

When we run the code, the will output be:

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

When we run the code, the will output be:

local x: 10
global x: 5

In above code, we used same name x for both global variable and local variable. We get different result when we print 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 the foo() it outputs local x: 10, this is called local scope of variable.

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


Nonlocal Variables

Nonlocal variable are used in nested function whose local scope is not defined. This means, the variable can be neither in the local nor the global scope.

Let’s see an example on how a global variable is created in Python.

We use nonlocal keyword to create nonlocal variable.

Example 6: Create a nonlocal variable

defouter():
x = “local”
def inner():
nonlocal x
x = “nonlocal”
print(“inner:”, x)
inner()
print(“outer:”, x)
outer()
Run

When we run the code, the will output be:

inner: nonlocal
outer: nonlocal

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

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

When we run the code, the will output be:

inner: nonlocal
outer: nonlocal

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

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

 


Python Global Keyword

In this article, you’ll learn about the global keyword, global variable and when to use global keywords.

Before reading this article, make sure you have got some basics of Python Global, Local and Nonlocal Variables.


Introduction to global Keyword

In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.


Rules of global Keyword

The basic rules for global keyword in Python are:

  • When we create a variable inside a function, it’s local by default.
  • When we define a variable outside of a function, it’s global by default. You don’t have to use global keyword.
  • We use global keyword to read and write a global variable inside a function.
  • Use of global keyword outside a function has no effect

Use of global Keyword (With Example)

Let’s take an example.

Example 1: Accessing global Variable From Inside a Function

1
2
3
4
5
6
c = 1 # global variable
def add():
print(c)
add()
Run

When we run above program, the output will be:

1

However, we may have some scenarios where we need to modify the global variable from inside a function.


Example 2: Modifying Global Variable From Inside the Function

1
2
3
4
5
6
7
c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
Run

When we run above program, the output shows an error:

UnboundLocalError: local variable 'c' referenced before assignment

This is because we can only access the global variable but cannot modify it from inside the function.

The solution for this is to use the global keyword.


Example 3: Changing Global Variable From Inside a Function using global

1
2
3
4
5
6
7
8
9
c = 0 # global variable
def add():
global c
c = c + 2 # increment by 2
print(“Inside add():”, c)
add()
print(“In main:”, c)
Run

When we run above program, the output will be:

Inside add(): 2
In main: 2

In the above program, we define c as a global keyword inside the add() function.

Then, we increment the variable c by 1, i.e c = c + 2. After that, we call the add() function. Finally, we print global variable c.

As we can see, change also occured on the global variable outside the function, c = 2.


Global Variables Across Python Modules

In Python, we create a single module config.py to hold global variables and share information across Python modules within the same program.

Here is how we can share global variable across the python modules.

Example 4 : Share a global Variable Across Python Modules

Create a config.py file, to store global variables

  1. a = 0
  2. b = "empty"

Create a update.py file, to change global variables

  1. import config
  2. config.a = 10
  3. config.b = "alphabet"

Create a main.py file, to test changes in value

  1. import config
  2. import update
  3. print(config.a)
  4. print(config.b)

When we run the main.py file, the output will be

10
alphabet

In the above, we create three files: config.pyupdate.py and main.py.

The module config.py stores global variables of a and b. In update.py file, we import the config.py module and modify the values of a and b. Similarly, in main.py file we import both config.py and update.py module. Finally, we print and test the values of global variables whether they are changed or not.


Global in Nested Functions

Here is how you can use a global variable in nested function.

Example 5: Using a Global Variable in Nested Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def foo():
x = 20
def bar():
global x
x = 25
print(“Before calling bar: “, x)
print(“Calling bar now”)
bar()
print(“After calling bar: “, x)
foo()
print(“x in main : “, x)
Run

The output is :

Before calling bar: 20
Calling bar now
After calling bar: 20
x in main : 25

In the above program, we declare global variable inside the nested function bar(). Inside foo() function, x has no effect of global keyword.

Before and after calling bar(), the variable x takes the value of local variable i.e x = 20. Outside of the foo() function, the variable x will take value defined in the bar() function i.e x = 25. This is because we have used global keyword in x to create global variable inside the bar() function (local scope).

If we make any changes inside the bar() function, the changes appears outside the local scope, i.e. foo().

.END

 

 

 

Categories: Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.