問題描述
兩個不同定義之間的變量 (Variable between two different definitions)
我想從 b() 調用 var d。但我得到這個錯誤。我聽說你可以有全局變量,我試過但沒有成功。
錯誤:
Traceback (most recent call last):
File "C:/Users/user2/Desktop/def.py", line 9, in <module>
a()
File "C:/Users/user2/Desktop/def.py", line 3, in a
if d == 0:
NameError: name 'd' is not defined
代碼:
def a():
if d == 0:
print(correct)
else:
print (not correct)
def b():
d = 0
a()
參考解法
方法 1:
You can define the variable outside the function and it should work. Although it is better to pass as argument.
d=0
correct="It is correct"
notcorrect="It is not correct"
def a():
if d == 0:
print(correct)
else:
print(notcorrect)
a()
方法 2:
You can use variables of a "parent" scope, even if it's better to pass them to the method. Your function b()
is never called in your example. And definitions in a function are just defined for this functions or functions called from there.
I would recommend you to read about scopes: https://pythonspot.com/scope/ (there are tons of other tutorials out there, just use your search engine ;))
what you could do:
d = 0
a() # correct
what you could do as well:
def b():
d = 0
a()
b() # correct
but what you SHOULD do is probably something like:
def b():
d = 0
return d
def a(d):
...
a(b()) # correct
global variables exist in python, but especially for beginners it often seems to be an easy solution, but as soon as your code grows this can become very complex if not used carefully.. understanding scopes of variables and how to pass them into other functions is the way to go.
方法 3:
The code will definitely show an error because the variables created within the function are for that function only called local variables, and the variable created outside the function are called global variables.
hence,
- you simply have to create the variable outside the function globally then it will not shows error.
def a(d):
if d == 0:
print("correct")
else:
print ("not correct")
#################
a(0)
- or else you can use inbuilt function
global()
if you want to use the variable inside the different functions. and make sure you have the functions as well.
(by Benjamin Dixon、David Duran、Lukr、Rohit)