#declare a global variable a = 23 def print_a_variable(): print(a) #Printing it works just fine def change_a_variable(): a = 100000 print(a) #seems to work but a is actually a new variable print_a_variable()
change_a_variable()
print(a)
Output:
23 100000 23
If you use the keyword global in your function then the global is no longer read-only.
#declare a global variable a = 23 def print_a_variable(): #global a - not needed here because we can have readonly access to globals print(a) #Printing a works just fine def change_a_variable(): global a #If you want to change the global then it has to be declared here a = 100000 print(a) #a is declared local and doesn't effect the global variable a print_a_variable() change_a_variable() print(a) #a is still 23
Output:
23 100000 100000
No comments:
Post a Comment