How to use Global Variables in a Function

Python : How to use Global Variables in a Function ?

In this article, we’ll look at the differences between local and global variables, as well as how to access and change both global and local variables with the same name within a function.

Global variables and local variables are the two types of variables.
Global variables have a scope that spans the entire program, while local variables have a scope that is restricted to the role in which they are specified.

Use of Global Variables in a Function

1)Global Variable

In a program, a global variable is a variable specified outside of the subroutine or function. It has a global reach, which means it would be useful for the duration of the program. As a result, unless it is shadowed, it can be accessed within the program by any feature specified within the program.

2)Advantages of Global Variable

  • The global variable can be accessed from any function or module in a program.
  • You only need to declare global variables once outside of the modules.
  • It is suitable for storing “constants” because it lets you maintain continuity.
  • When multiple functions need to access the same data, a global variable comes in handy.

3)Disadvantages of Global Variable

  • If there are so many global variables declared, they will remain in memory until the program is finished. This can result in an Out of Memory error.
  • Any feature has the ability to change data. The value of the global variable can be changed by any expression in the program. In multi-tasking situations, this may lead to unexpected outcomes.
  • If global variables are no longer used as a result of code refactoring, you’ll need to update all of the modules that use them.

4)Local Variable vs Global Variable

A local variable is defined within a function, while a global variable is defined outside of any function or class, i.e. in global space. A global variable may be used in any function, while a local variable has only the scope of the function in which it is specified.

Example:

# declaring global variable
weight = 60

def test():
    # declaring  local variable
    age = 19
    print('weight = ', weight)
    print('age = ', age)

test()

Output:

weight =  60
age =  19

Here, ‘weight’ is a global variable that can be accessed from within function test() too, while ‘age’ is a local variable that can only be accessed from within function test().

5)Global Variables and Local Variables with same name

# declaring global variable
weight = 60

def test():
    # declaring  local variable with same name
    weight = 19

# printing the weight before calling test()
print('weight = ', weight)
test()
# printing the weight after calling test()
print('weight = ', weight)

Output:

weight =  60
weight =  60

Explanation:

In this case, ‘weight’ is a global variable, and the test() function has a local variable of the same name. If both variables have the same name, a function would prefer the local variable over the global variable. As a result, in the preceding code, when we changed the ‘weight’ variable within the function, the change was not reflected outside the function. Since total variable is treated as a local variable within feature test().

6)Use of global Keyword

If your function has a local variable with the same name as a global variable and you want to change the global variable within the function, use the ‘global’ keyword before the variable name at the start of the function.

It will cause the function to refer to the global variable total whenever it is called.

Below is the implementation:

# declaring global variable
weight = 60

def test():
    # within function, refer to global variable 'weight'
    global weight
    if(weight > 50):
        weight = 70

# printing the weight before calling test()
print('weight = ', weight)
test()
# printing the weight after calling test()
print('weight = ', weight)

Output:

weight =  60
weight =  70

As you can see, the changes you made to the global variable total are now noticeable outside of the feature as well.

When the global keyword is used with a variable inside a function, the local variable is hidden.

7)Using globals()

Since the ‘global’ keywords hide the local variable of the same name, there is another way to access both the local and global variables within a function, which is the global() function.
globals() returns a dictionary of elements in the current module, which we can use to access and change global variables without using the ‘global’ keyword.

# declaring global variable
weight = 60

def test():
    # golbal list
    global_list = globals()
    global_list['weight'] = 20
    weight = 30
    print('Local weight = ', weight)

# printing the weight before calling test()
print('weight = ', weight)
test()
# printing the weight after calling test()
print('weight = ', weight)

Output:

weight =  60
Local weight =  30
weight =  20

Explanation:

As you can see, we have a local variable and a global variable with the same name, complete, and we changed both within the feature. Instead of using the keyword ‘global,’ use the dictionary returned by globals() to refer to a global variable. It will not conceal a local variable within the feature.
Related Programs: