我确保在main()之前有全局,而且我确实给变量useraction赋了一个值。为什么它仍然说它是未定义的?
import os.path
from os import path
shoppinglist = []
global useraction
def main():
Displaylist()
RunItemAction()
def Displaylist():
i = 0
if (len(shoppinglist)>0):
while (i<=len(shoppinglist)):
print(shoppinglist[i] +"\n")
i+=1
useraction = str(input("Do you want to add, remove, or search for an item? "))
useraction = useraction.upper()
def RunItemAction():
if( useraction == "ADD"):
AddItem()
我认为你应该这样使用它。
import os.path
from os import path
shoppinglist = []
useraction="" # or any default value you want to give
def main():
Displaylist()
RunItemAction()
def Displaylist():
global useraction
i = 0
if (len(shoppinglist)>0):
while (i<=len(shoppinglist)):
print(shoppinglist[i] +"\n")
i+=1
useraction = str(input("Do you want to add, remove, or search for an item? "))
useraction = useraction.upper()
def RunItemAction():
global useraction
if( useraction == "ADD"):
AddItem()
任何在全局作用域定义的名称,根据定义,都是全局的。
在全局范围内定义的任何名称,根据定义,都是全局的。global
语句用于 另一个 的作用域来标记一个原本是本地的名称为全局的。
import os.path
from os import path
shoppinglist = []
def main():
Displaylist()
RunItemAction()
def Displaylist():
global useraction
i = 0
if (len(shoppinglist)>0):
while (i<=len(shoppinglist)):
print(shoppinglist[i] +"\n")
i+=1
useraction = str(input("Do you want to add, remove, or search for an item? "))
useraction = useraction.upper()
def RunItemAction():
global useraction
if( useraction == "ADD"):
AddItem()
也就是说,根本就不要使用全局变量。将参数传递给函数,并让它们返回值。