Reputation: 11
func 1
def num1():
global h
h=7
func 2
def num2():
print(h)
When I call this function:
num2()
Here, it should print the value of h
which is globally declared in func 1
.
But it is giving NameError
why?? Anyone answer me plz..
Upvotes: 1
Views: 737
Reputation: 530922
Defining num1
doesn't actually define h
. The definition of num1
just says that, when you call num1
, it will assign to the global name h
. If h
doesn't exist at that time, it will be created. But defining num1
isn't sufficient to create h
.
You need to ensure that h
exists before num2
is called. You can do that by assigning to h
yourself, or calling num1
.
>>> num2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in num2
NameError: name 'h' is not defined
>>> h = 3
>>> num2()
3
>>> del h
>>> num2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in num2
NameError: name 'h' is not defined
>>> num1()
>>> num2()
7
Upvotes: 0
Reputation: 175
to access the global variable h
through num2()
make sure to call num1()
before calling num2()
Upvotes: 1