Skip to content

Python Set global variable in function

  • by

In Python, You can use the global keyword to Set a global variable in a function. If you want to simply access a global variable you just use its name. However, to change its value you need to use the global keyword.

Python Set a global variable in a function examples

Simple example code.

x = 10  # define a global variable


def set_global_variable():
global x
x = 20 # set the value


print(x)
set_global_variable()
print(x)

Output:

Python Set global variable in function

Is it possible to define global variables in a function in Python?

Answer: Yes this is possible but not needed.

def function(arguments):
    global var_name
    var_name = value #must declare global prior to assigning value

Comment if you have any doubts or suggestions on this Python global variable topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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