Python Global, Local and Nonlocal variables
Global Variables In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function. Let's see an example on how a global variable is created in Python. Example 1: Create a Global Variable When we run the code, the will output be: x inside : global x outside: global In above code, we created x as a global variable and defined a foo() to print the global variable x . Finally, we call the foo() which will print the value of x . What if you want to change value of x inside a function? When we run the code, the will output be: UnboundLocalError: local variable 'x' referenced before assignment The output shows an error because Python treats x as a local variable and x is also not defined inside foo() . To make this work we use global keyword, t...

Comments
Post a Comment