Kumar Amit
Kumar Amit

Reputation: 11

How to call variable from another function by declaring global in python?

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

Answers (2)

chepner
chepner

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

lorem_bacon
lorem_bacon

Reputation: 175

to access the global variable h through num2() make sure to call num1() before calling num2()

Upvotes: 1

Related Questions