1

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..

3
  • try adding global h to the second function Commented May 24, 2020 at 17:58
  • and another thing: using global variables to share variables between functions is a bad habbit (unless you use them as constant variables such as MAX_VALUE = 100 where you want the max to be the same everywhere. but in this case you don't change its value). a better practice is either pass the variable as a parameter to the functions that use it , or put them both under a class and change this global variable to a class attribute Commented May 24, 2020 at 18:03
  • 1
    You have to actually call num1 for h to be defined. Commented May 24, 2020 at 18:06

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.