+ 1

Why is my function getting this error when im putting it to a global?

Im just playing with the python (global) function. An Error will appear why? def h(): global x x = "Hi" print(x + " Guys") print(x) NameError: name 'x' is not defined It is supposed to print "Hi" but it didnt why?

15th Jun 2020, 5:48 PM
slawbear
slawbear - avatar
4 Answers
+ 10
Here is your sample reworked: x = 'something' def h(): global x x = "Hi" print(x + " Guys") print(x) # result= 'something' h() # result = 'Hi Guys' print(x # result = 'Hi'
15th Jun 2020, 6:28 PM
Lothar
Lothar - avatar
+ 6
Mabe it's because you have never called h().
15th Jun 2020, 5:49 PM
Lisa
Lisa - avatar
+ 1
The keyword 'global' is reserved for external reference, i. e. the variable used as global within a function must be defined in the upper scope for that function. So, in your case if x is not defined before h() the NameError is justified.
15th Jun 2020, 6:14 PM
Anubhav Mattoo
Anubhav Mattoo - avatar
+ 1
global x, in simple terms, means: 'If we assign anything to x, let's do that in the global scope!' Before you call your function, no assigning to x has taken place. So there is no x when you try to print it.
15th Jun 2020, 9:22 PM
HonFu
HonFu - avatar