+1 vote
2 views
in Python by (4.1k points)
edited by

In a function, How to create and use a global variable?

How can I use it in other functions?

Is it compulsory to store the value of global variable in a local variable to use it in a function?

2 Answers

0 votes
by (10.9k points)

If you want to refer to a global variable in a function you have to use the “global” keyword:

Ex-

gvar=1

#you need to refer to global to modify the value

def set_gvar():

global gvar    

    gvar = 2

#no need to declare global to read value

def print_gvar():

print(gvar)    

 set_gvar()

print_glvar()  

# prints 2

 The main reason for using the “global “ keyword is to make Python sure that you know what you are dealing with and not mistaking it with a local variable. If “global” keyword is not mentioned, Python will implicitly declare it as local.

 Hope this answer helps!

0 votes
by (107k points)

Let's say you have got a module like this:

myGlobal = 4

def func1():

    myGlobal = 3

def func2():

    print myGlobal

func1()

func2()

You might be expecting this to print 3, but instead, it prints 4. As has already been mentioned, if you add a 'global' declaration to func1(), then func2() will print 42.

def func1():

    global myGlobal

    myGlobal = 3

You can use the following video tutorials to clear all your doubts:-

Related questions

0 votes
2 answers
0 votes
1 answer
asked Aug 5, 2019 in Python by Sammy (47.8k points)
+1 vote
2 answers
asked May 29, 2019 in R Programming by Suresh (3.4k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...