How do you pass a global variable to a function in python?

Within a Python scope, any assignment to a variable not already declared within that scope creates a new local variable unless that variable is declared earlier in the function as referring to a globally scoped variable with the keyword global.

Let's look at a modified version of your pseudocode to see what happens:

# Here, we're creating a variable 'x', in the __main__ scope.
x = 'None!'

def func_A():
  # The below declaration lets the function know that we
  #  mean the global 'x' when we refer to that variable, not
  #  any local one

  global x
  x = 'A'
  return x

def func_B():
  # Here, we are somewhat mislead.  We're actually involving two different
  #  variables named 'x'.  One is local to func_B, the other is global.

  # By calling func_A(), we do two things: we're reassigning the value
  #  of the GLOBAL x as part of func_A, and then taking that same value
  #  since it's returned by func_A, and assigning it to a LOCAL variable
  #  named 'x'.     
  x = func_A() # look at this as: x_local = func_A()

  # Here, we're assigning the value of 'B' to the LOCAL x.
  x = 'B' # look at this as: x_local = 'B'

  return x # look at this as: return x_local

In fact, you could rewrite all of func_B with the variable named x_local and it would work identically.

The order matters only as far as the order in which your functions do operations that change the value of the global x. Thus in our example, order doesn't matter, since func_B calls func_A. In this example, order does matter:

def a():
  global foo
  foo = 'A'

def b():
  global foo
  foo = 'B'

b()
a()
print foo
# prints 'A' because a() was the last function to modify 'foo'.

Note that global is only required to modify global objects. You can still access them from within a function without declaring global. Thus, we have:

x = 5

def access_only():
  return x
  # This returns whatever the global value of 'x' is

def modify():
  global x
  x = 'modified'
  return x
  # This function makes the global 'x' equal to 'modified', and then returns that value

def create_locally():
  x = 'local!'
  return x
  # This function creates a new local variable named 'x', and sets it as 'local',
  #  and returns that.  The global 'x' is untouched.

Note the difference between create_locally and access_only -- access_only is accessing the global x despite not calling global, and even though create_locally doesn't use global either, it creates a local copy since it's assigning a value.

The confusion here is why you shouldn't use global variables.


Global Variables

Variables that are created outside of a function (as in all of the examples above) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

Example

Create a variable outside of a function, and use it inside the function

x = "awesome"

def myfunc():
  print("Python is " + x)

myfunc()

Try it Yourself »

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

Example

Create a variable inside a function, with the same name as the global variable

x = "awesome"

def myfunc():
  x = "fantastic"
  print("Python is " + x)

myfunc()

print("Python is " + x)

Try it Yourself »



The global Keyword

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.

To create a global variable inside a function, you can use the global keyword.

Example

If you use the global keyword, the variable belongs to the global scope:

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

Try it Yourself »

Also, use the global keyword if you want to change a global variable inside a function.

Example

To change the value of a global variable inside a function, refer to the variable by using the global keyword:

x = "awesome"

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

Try it Yourself »



Python also uses variables to hold data. They also have a name and a type; however, in python, you don't have to declare the data type. Instead, you can create a python variable as follows.

class_number = 4;

In the above example, the variable 'class_number' has the value of 4; it is an integer data type. And unlike other programming languages, you don't need to declare a variable without initializing. 

What Does Variable Scope in Python Mean?

Variable scope means the area in which parts of a program can access the variable. There are four variable scopes in python:

  1. Local
  2. Global
  3. Enclosing
  4. Built-in

In this article, you will learn the first two types. You will learn to create python variables with local and global scope.

What Is the Global Variable In Python?

In the programming world, a global variable in Python means having a scope throughout the program, i.e., a global variable value is accessible throughout the program unless shadowed.  

A global variable in Python is often declared as the top of the program. In other words, variables that are declared outside of a function are known as global variables.

You can access global variables in Python both inside and outside the function.  

Syntax:

X = “sampleGlobalValue”

Def fn1():

How to Create Global Variables in Python?

To create a global variable in Python, you need to declare the variable outside the function or in a global scope.

Example: 

GlobalVariableinPython_1

Output:

GlobalVariableinPython_2 

How to Access the Global Variable Inside and Outside of the Function?

Example:

GlobalVariableinPython_3 

Output:

GlobalVariableinPython_4 

In the example depicted above, you saw a global variable declared and accessed both inside and outside of the function.  

So, you are accessing the value both inside and outside of the function, which is fine, but what happens if you try to modify the global scope variable value inside a function? 

See the example mentioned below to understand better. 

Example:

GlobalVariableinPython_5. 

Output:

GlobalVariableinPython_6 

As it is evident, this throws an error. When you try to modify the global variable value inside a function, it will throw UnboundLocalError, because while modifying Python treats x as a local variable, but x is also not defined inside the function (myfunc()).

That’s where the Global keyword comes into the picture. You will see the usage of Global Keywords in the following sections.

How to Create Variables With Local Scope in Python with Examples?

A local variable's scope is a function in which you declared it. To access the variable, you have to call the corresponding function. For example, you can create a local variable as shown below.

def superfunc()

#defining a function

x = fantastic

#defining a local variable

print("Python is" + x)

#accessing a local variable

superfunc()

#calling the function

Global Keyword

Global keyword is used to modify the global variable outside its current scope and meaning. It is used to make changes in the global variable in a local context. The keyword ‘Global’ is also used to create or declare a global variable inside a function.  

Usually, when you create a variable inside a function (a local variable), it can only be used within that function. That’s where the global keyword comes in the play, which helps to create global variables inside the function and which can be accessible in a global scope.

Syntax:

Def func():

Global variable

Example 1:

Use a global keyword to create a variable in the global scope.

GlobalVariableinPython_7 

Output:

GlobalVariableinPython_8 

Example 2:

Use a global keyword to change the value of the global variable inside the function.

GlobalVariableinPython_9 

Output:

GlobalVariableinPython_10 

You have seen what ‘global’ keywords are, their examples, and how to use global keywords. But Python has some basic rules to use the ‘global’ keyword.

Let’s see Global in Nested functions.

When you declare a global keyword variable inside the nested function and when you change the global keyword variable inside the nested function, it will reflect outside the local scope, since it is used as a global keyword.

Example:

Let's see an example for global in nested functions.

GlobalVariableinPython_11 

Output:

GlobalVariableinPython_12. 

You can see the above output for the global in nested functions. But maybe a quick following explanation will help for better understanding.

You have declared the global variable inside the inner() function, which is nested inside the main() function.

Before and after calling the inner(), the variable ‘integ’ takes the value of the local variable main i.e. integ = 20. Outside of the main() function, the variable ‘integ’ takes the value of the global keyword declared inside the inner() function i.e., integ = 20 as you used the global keyword inside the inner() function local scope. If you make any changes inside the inner() function global keyword variable ‘integ’, will reflect outside of the scope, as a behavior of the global keyword.

The fundamental rules of the ‘global’ keyword are as follows:

  • When you create a variable inside the function, it is in a local context by default
  • When you create or define a variable outside the function, by default it is a global context, there’s no need for a global keyword here
  • Global keywords can be used to read or modify the global variable inside the function
  • Using a global keyword outside of the function has no use or makes no effect.

How Can You Create Variables Using Global Scope in Python With Examples?

You can create a variable with global scope by initializing outside all the functions in a python program. And you can access the variable from anywhere in the python program. 

Creating a global variable is simple; you can do it as follows.

x = "wonderful"

#defining a global variable

def wonderfunc():

#declaring a function

print("Python is" + x)

#accessing the global variable

wonderfunc()

#calling the function

How to Use Global Keywords in Python With Examples?

If you use a variable inside a function, python thinks you are referring to a local variable. So use the global keyword to change a global variable within a python function. 

The following example shows the use of global keywords in a python program.

x = 5

#initializing a global variable

def life()

#defining a function

global x

#using global keyword 

x = x + 2

#changing the global variable

life()

#calling the function

print(x)

#accessing the global variable

Local Variables

The following example shows a mistake. 

Example 1: Accessing Local Variable Outside the Scope

def loc() 

#defining loc() function

y = "local"

# declaring y locally

loc()

# calling the function loc()

print(y)

# accessing the variable y

In the above program, you are trying to access 'y' defined in the function loc(). And the line print(y) will give you a Name Error: name 'y' is not defined. 

The following example shows how to rewrite the above program.

Example 2: Create a Local Variable

def loc()

#defining the function

y = "local"

# declaring the local variable

print(y)

#locally accessing the local variable

loc()

#calling a function

Global and Local Variables

As you can not access a local variable from outside a function, it does not matter if the global and the local variables have the same name. Below you can find an example where there are two variables. One is global, and the other is local. Both have the same name. 

Example1: Global Variable and Local Variable With the Same Name

x = 5; 

#initializing a global variable

def man():

#defining a function man()

x = 4

#initializing a local variable

print("local x:", x) 

# accessing a local variable

man()

#calling the man function

print("global x:", x)

#accessing a local variable

In the above example, the print function in the man () function accesses the local variable x with a value of 4. And the print function outside accesses the local variable with a value of 5.  

Difference Between Global and Local Variables

Let us see an example of how global and local variables behave in the same code.

Example:

GlobalVariableinPython_13 

Output:

GlobalVariableinPython_14 

Explanation:

Here in the program above, you declared x as a global and y as a local variable in the same program. Then it tried to modify the global variable using the global keyword in the local function and printing both gx and ly.

Once you called function1(), the value of gx became global global. As you tried to modify as gx*2, it printed ‘global’ two times. After this, you printed the local variable ly, which displayed the local variable value i.e., again ‘local’.

Difference Between Global and Nonlocal Variables

When a variable is either in local or global scope, it is called a nonlocal variable. Nonlocal variables are defined in the nested function whose scope is not defined.

Example:

GlobalVariableinPython_15. 

Output:

GlobalVariableinPython_16 

Explanation:

From the above program, it can be noticed that the nested function is innerfn(). Inside the innerfn(), you saw the use of a nonlocal keyword to create a nonlocal variable. The innerfn() is defined in the scope of outerfn(). If you make changes to the value of a nonlocal variable, they reflect in the local variable.

In conclusion, understanding the scope of python variables is essential for an error-free program. You can access the global variables from anywhere in the program. However, you can only access the local variables from the function. Additionally, if you need to change a global variable from a function, you need to declare that the variable is global. You can do this using the "global" keyword. 

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Conclusion

Variables are one of the most basic elements of a programming language. It is an abstraction layer for the memory cells that contain the actual value. Global, Local and Nonlocal types of variables help the programmer to access some values entirely in the program scope, or some values that are limited to within the function.

In this article, you learned what a global variable is in Python, how to define global variables in Python, how to declare a global variable in Python, what is a global keyword, when to use a global keyword, the difference between global, local, and nonlocal variables along with some working examples.  

Join Simplilearn's Python Training Course to learn more about this topic. This course will teach you the basics of Python, conditional statements, data operations, shell scripting, and Django. This certification course, which includes 38 hours of blended learning and 8 hours of online self-paced learning, will prepare you for a fulfilling career as a professional Python programmer by providing you with practical programming experience.

Have any questions for us? Leave them in the comments section of this article, and our experts will get back to you on them, as soon as possible!

Can we pass a global variable in a function Python?

Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.

How do you pass a variable to a function in Python?

How do I pass variables across functions?.
Initialize 'list' as an empty list; call main (this, at least, I know I've got right...).
Within defineAList(), assign certain values into the list; then pass the new list back into main().
Within main(), call useTheList(list).

How do you pass a global variable?

Passing global variables between languages.
Create a named common block that provides a one-to-one mapping of the C structure members. ... .
Declare the C structure as a global variable by putting its declaration outside any function or inside a function with the extern qualifier..

How do you make a global function in Python?

The basic rules for global keyword in Python are:.
When we create a variable inside a function, it is local by default..
When we define a variable outside of a function, it is global by default. ... .
We use global keyword to read and write a global variable inside a function..