Posts

Showing posts with the label global variables

20.Global,local and non local variables

Global Variables In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function. Let's see an example of how a global variable is created in Python. Example 1: Create a Global Variable x = "global"  def foo():         print("x inside:", x)   foo()  print("x outside:", x) Output x inside: global  x outside: global Global Variables can be modified in functions with the keyword global X=10 def inc():      global X      X=X+1 def dec():      global X      X=X-1 print(X)  # this will print 10 inc() print (X) # this will print 11 dec() dec() print (X) #this will print 9 Using Global and Local variables in the same code x = "global "   def foo():        global x        y = "local"        x = x * 2        print(x)        print(y)  foo() Output global global  local In t