Global Variables in Python

0
29

Those Variables which you create outside of a function are by-default global variables. This means that these variables can be used inside an outside functions.

Example:

x = " X is global variable."

def myfunc():
  print("Wow!! " + x)

myfunc()

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

 

x = "X is a global variable."

def myfunc():
  x = "I am not Global."
  print("Oops!! " + x)

myfunc()

print("Wow!! " + x)

 

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.

To create a global variable inside a function, you can use the global keyword.

def myfunc():
  global x
  x = "I am global now."

myfunc()

print("Hey!! " + x)