Understand Python Global Variable for Beginners – Python Tutorial

By | July 31, 2019

Python global variable is defined outside a function. It will work on the whole function if there is no the same named variable. In this tutorial, we will introduce how to use python global variable correctly.

python global and local variable

Define a global variable

str = "this is global variable"

This variable is defined outside a function, it is a global variable.

Define a function

def fun():
    print(str)

In this function, we can find str variable can work in this function and str is outside it.

The the output is:

this is global variable

If the name of a variable in function is same to the global variable, the global variable will not work in this function.

Define a function with a local variable named str.

def fun2():
    str = "this is a local variable"
    print(str)

In this function, we will find the name of local variable is same to the outside str, which means the outside global variable will not work in this function.

As to code:

fun2()
print(str)

You will get output:

this is a local variable
this is global variable

How to make outside global variable str works in function. You should use global keyword.

def fun3():
    global str
    str = "this is a local variable"
    print(str)

Then as to code:

fun3()
print(str)

You will get output:

this is a local variable
this is a local variable

By using global keyword, outside global variable str can work in fun3().

Leave a Reply

Your email address will not be published. Required fields are marked *