How to access global variable in Python
Variables that are created outside a function are known as global variables. Global variables can be used by everyone, both inside of functions and outside.
To access a global variable inside a function there is no need to use global keyword.
# global variable a = 2 b = 9 def mul(): c = a * b return c print("{} * {} = {}".format(a, b, mul()))
Output:
2 * 9 = 18
Using global keyword:
a = 20 def modify(): # declare a global keyword global a a = a + 12 print("The value of a inside a function: ", a) modify() print("The value of a outside a function: ", a)
Output:
The value of a inside a function: 32 The value of a outside a function: 32
Subscribe
Login
Please login to comment
0 Discussion