+ 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?
5 odpowiedzi
+ 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'
+ 6
Mabe it's because you have never called h().
+ 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.
+ 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.