How to Use Global Variables In a Python Function?

Summary: Use the global keyword to declare a global variable inside the local scope of a function so that it can be modified or used outside the function as well. To use global variables across modules create a special configuration module and import the module into our main program. The module is available as a global name in our program. As each module has a single instance, any changes to the module object get reflected everywhere.

Problem: Given a function; how to use a global variable in it?

Example:

def foo():
  # Some syntax to declare the GLOBAL VARIABLE "x"
  x = 25 # Assigning the value to the global variable "x"

def func():
# Accessing global variable defined in foo()   
  y = x+25
  print("x=",x,"y=",y)

foo()
func()

Expected Output:

x= 25 y= 50

In the above example, we have been given a function named foo() which returns a global variable x such that the value of x can be used inside another function named func(). Let us have a quick look at how we can use the global keyword to resolve our problem.

Solution: Using The Global Keyword

We can use the global as a prefix to any variable in order to make it global inside a local scope.

def foo():
  global x
  x = 25

def func():
  y = x+25
  print("x=",x,"y=",y)

foo()
func()

Output:

x= 25 y= 50

Now that we already know our solution, we must go through some of the basic concepts required for a solid understanding of our solution. So, without further delay let us discuss them one by one.

๐ŸŒ Recommended Tutorial: How to Return a Global and Local Variable from a Python Function?

Variable Scope In Python

The scope of a variable is the region or part of the program where the variable can be accessed directly. Let us discuss the different variable scopes available in Python.

โ– Local Scope

When a variable is created inside a function, it is only available within the scope of that function and ceases to exist if used outside the function. Thus the variable belongs to the local scope of the function.

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

foo()

Output:

local

โ– Enclosing Scope

An enclosing scope occurs when we have nested functions. When the variable is in the scope of the outside function, it means that the variable is in the enclosing scope of the function. Therefore, the variable is visible within the scope of the inner and outer functions.

Example:

def foo():
  scope = "enclosed"
  def func():
    print(scope)
  func()

foo()

output:

enclosed

In the above example, the variable scope is inside the enclosing scope of the function foo() and available inside the foo() as well as func() functions.

โ– Global Scope

A global variable is a variable that is declared in a global scope and can be used across the entire program; that means it can be accessed inside as well outside the scope of a function. A global variable is generally declared outside functions, in the main body of the Python code.

Example:

name = "FINXTER"

def foo():
    print("Name inside foo() is ", name)


foo()
print("Name outside foo() is :", name)

Output:

Name inside foo() is FINXTER
Name outside foo() is : FINXTER

In the above example, name is a global variable that can be accessed inside as well as outside the scope of the function foo(). Let’s check what happens if you try to change the value of the global variable name inside the function.

name = "FINXTER"

def foo():
    name = name + "PYTHON"
    print("Name inside foo() is ", name)


foo()

Output:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    foo()
  File "main.py", line 4, in foo
    name = name + "PYTHON"
UnboundLocalError: local variable 'name' referenced before assignment

We get an UnboundLocalError in this case, because Python treats name as a local variable inside foo() and name is not defined inside foo(). If you want to learn more about the UnboundLocalError and how to resolve it, please read it in our blog tutorial here.

โ– Built-In Scope

The built-in scope is the widest scope available in python and contains keywords, functions, exceptions, and other attributes that are built into Python. Names in the built-in scope are available all across the python program. It is loaded automatically at time of executing a Python program/script.

Example:

x = 25
print(id(x))

Output:

140170668681696

In the above example, we did not import any module to use the functions print() or id(). This is because both of them are in the built-in scope.

Having discussed the variable scopes in Python, let us discuss about a couple of very important keywords in Python in relation to the variable scopes.

Use Global Variables Inside A Function Using The global Keyword

We already read about the global scope where we learned that every variable that is declared in the main body and outside any function in the Python code is global by default. However, if we have a situation where we need to declare a global variable inside a function as in the problem statement of this article, then the global keyword comes to our rescue. We use the global keyword inside a function to make a variable global within the local scope. This means that the global keyword allows us to modify and use a variable outside the scope of the function within which it has been defined.

Now let us have a look at the following program to understand the usage of the global keyword.

def foo():
    global name
    name = "PYTHON!"
    print("Name inside foo() is ", name)

foo()
name = "FINXTER "+name
print("Name outside foo() is ", name)

Output:

Name inside foo() is  PYTHON!
Name outside foo() is  FINXTER PYTHON!

In the above example, we have a global variable name declared inside the local scope of function foo(). We can access and modify this variable outside the scope of this variable as seen in the above example.

โƒ POINTS TO REMEMBER

  • A variable defined outside a function is global by default.
  • To define a global variable inside a function we use the global keyword.
  • A variable inside a function without the global keyword is local by default.
  • Using the global keyword for a variable that is already in the global scope, i.e., outside the function has no effect on the variable.

Global Variables Across Modules

In order to share information across Python modules within the same piece of code, we need to create a special configuration module, known as config or cfg module. We have to import this module into our program. The module is then available as a global name in our program. Because each module has a single instance, any changes to the module object get reflected everywhere.

Let us have a look at the following example to understand how we can share global variables across modules.

Step 1: config.py file is used to store the global variables.

Step 2: modify.py file is used to change global variables.

Step 3: main.py file is used to apply and use the changed values of the global variable.

Output After Executing main.py

The nonlocal Keyword

The nonlocal keyword is useful when we have a nested function, i.e., functions having variables in the enclosing scope. In other words if you want to change/modify a variable that is in the scope of the enclosing function (outer function), then you can use the nonlocal keyword.

Example:

def foo():
  a = 25
  print("Value of 'a' before calling func = ",a)
  def func():
    nonlocal a
    a=a+20
    print("Value of 'a' inside func = ",a)
  func()
  print("Value of 'a' after exiting func = ",a)

foo()

Output:

Value of 'a' before calling func =  25
Value of 'a' inside func =  45
Value of 'a' after exiting func =  45

From the above example it is clear that if we change the value of a nonlocal variable the value of the local variable also changes.

Conclusion

The key points that we learned in this article are:

  1. Variable Scopes:
    • Local Scope
    • Enclosing Scope
    • Global Scope
    • Built-in Scope
  2. Important Keywords:
    • The global Keyword
      1. How to use a global variable inside a function?
      2. How to use a global variable across modules?
    • The nonlocal Keyword

I hope you found this article useful and you can easily apply the above concepts in your code. Please subscribe and stay tuned for more interesting articles.

Where to Go From Here?

Enough theory. Letโ€™s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. Thatโ€™s how you polish the skills you really need in practice. After all, whatโ€™s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

๐Ÿš€ If your answer is YES!, consider becoming a Python freelance developer! Itโ€™s the best way of approaching the task of improving your Python skillsโ€”even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar โ€œHow to Build Your High-Income Skill Pythonโ€ and learn how I grew my coding business online and how you can, tooโ€”from the comfort of your own home.

Join the free webinar now!