Global Variable Declarations In Python

Share Your Love

There are 2 ways we use global variables in python.

Normal Global Variable:

Variables are created outside the function, are know as Global Variables.

Global variables can be used by everyone, both inside of function and outside.

Example Of Global Variable:

Global Variable Used Inside Function:

x = "Python"

def myFun():
   print("Welcome To "+x)

myFun()

The output of above code is,

Welcome To Python

Then, if you create a same variable inside the function, the variable will be local and only used inside the function.

The global variable with same name as it was global with the original value.

Example:

Global Variable With Same Name Inside The Function.

x = "Tremendous"

def myfunc():
  x = "Mind-blowing"
  print("Python is " + x)

myfunc()

print("Python is " + x)

The output of above code,

Python is Mind-blowing
Python is Tremendous

There is another way to use or declare global variable,

Generally, when you create a variable inside the function, that variable can only be used in locally.

But, when you create a global variable inside the function, we use global keyword.

def myfunc():
  global x
  x = "Mind-Blowing"

myfunc()

print("Python is " + x)

The output is,

Python is Mind-Blowing

Then another example where inside and outside of function the variable is same,

x = "fantastik"
def myfunc():
  global x
  x = "Mind-Blowing"

myfunc()

print("Python is " + x)

The output is,

Python is Mind-Blowing

Because the above code x is a global by keyword global. But outside function x is declared and initialize the value where as within function also initialize the value with Mind-Blowing.

So python always access the recent values.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter