我正在处理一个任务,其中我需要使用定义函数中定义的变量,在定义循环之外,代码是:
def startmenu(): #this is to call back here at any time
startmenuoption = 1
while startmenuoption == 1:
startoption = input("Would you like to create, check or quit?")
if startoption in ["Check", "check"]:
print("You chose check!")
startmenuoption = 0
elif startoption in ["Create", "create"]:
print("You chose create!")
startmenuoption = 0
elif startoption in ["Quit", "quit"]:
print("You quit!")
startmenuoption = 0
else:
print("Invalid reason try again!")
startmenu()
if startoption in ["Check"]:
print("Checking!")
else:
print("Okay!")
我知道移除定义循环似乎是一个简单的选择,但这正是我想要避免的
有几个解决办法。您可以将其作为参数传递到函数中,并在调用startmenu()之前对其进行定义,例如:
startoption=无 开始菜单(开始选项)
也可以返回值
ans=开始菜单() 在“开始”菜单中返回“开始”选项
要访问函数中的变量,可以这样做:
或者只使用
global variable
,您可以使用global
在函数中访问和修改它注意:我建议使用
global
而不是第一种方法。将
if..else
部分移到方法相关问题 更多 >
编程相关推荐