Global Variable in Python

WHAT IS THE 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


Posted

in

Tags:

Comments

Leave a Reply