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()
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)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Python program are in Python 3, so it may change its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.