x = 5 #Any variable outside a function is already a global variable
def GLOBAL():
global y #if a variable is inside a function, use the 'global' keyword to make it a global variable
y = 10 # now this variable (y) is global
# Python global variable
# Probably should not use this, just pass in arguments
x = 0 # variable is in outer scope
print(x) # prints x (0)
def use_global_variables():
# if using a global variable, the variable will not need to be mention while calling the function
global x # calling the x variable from a function
x += 1
print(x) # prints x after adding one in the function (1)
use_global_variables
=============================================
# Output:
0
1
"""
Through the globals() function, one can bind a variable to a set
as illustrated below. name str variable was both bound to different
sets and used to modify these sets.
"""
name = "set"
set1 = set()
set2 = set()
set3 = set()
for i in range(1, 4):
globals()[name + str(i)].add(i) # access ith set and add value of i to it
print(set1) # {1}
print(set2) # {2}
print(set3) # {3}
#Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
name = "Abdullah" # creates global variable
def func():
global name # calls the name variable from global scope
name = "Kemal" # Changes name variable
func()
print(name) # global name variable will be changed because of the global keyword