WHAT IS THE GLOBAL VARIABLE IN PYTHON

Global Variable in Python

Global Variables in python are the Variables that are created outside of a function. Global variables can be used anywhere by everyone within the program.

To create a global variable inside a function, you can use the “global” keyword and its scope will be global.

Example-

x=”globalVariable1″     #variable declaration

y=”globalVariable2″     #variable declaration

def myfunction():         #user function defined

    y=”privateVariable” #private variable available within myfunction()

    global z                      #keyword global defines global variable in function

    z=”globalVariable3″ #assigning value to variable

    print(x)                      #access global variable x

    print(y)                      #access private variable y instead of global variable y

    print(z)                      #access to variable declared as global in the function

myfunction()                #call to myfunction()

print(x)                          #access global variable x

print(y)                         #access global variable y

print(z)                         #acces of variable outside the function

Output:-

globalVariable1

privateVariable

globalVariable3

globalVariable1

globalVariable2

globalVariable3


Leave a Reply

Your email address will not be published. Required fields are marked *