Skip to content

Create Python global variables in a function & Use in Other Functions

  • by

A variable declared outside of the function or in the global scope (class level) is known as Global Variables in Python. These are defined and declared outside a function and we need to use them inside a function.

Declare the Global variable when you want to use the same variable for the rest of the program.

How to create or use global variables in a function?

Answer: Simpl uses a global variable in other functions by declaring it as global in each function that assigns to it. See the below example.

test = 0

def set_test_to_one():
    global test    # Needed to modify global copy of test
    test = 1

def print_test():
    print(test)     # read value of test

set_test_to_one()
print_test()       

Output: 1

Why using a global keyword? because defining a Global variable is not a good IDE and python wants to make sure that you really want to use global variables.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python program are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading