在定义循环外使用变量,当在

2024-10-06 10:21:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个任务,其中我需要使用定义函数中定义的变量,在定义循环之外,代码是:

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!")

我知道移除定义循环似乎是一个简单的选择,但这正是我想要避免的


Tags: toinyouif定义checkcreatequit
3条回答

有几个解决办法。您可以将其作为参数传递到函数中,并在调用startmenu()之前对其进行定义,例如:

startoption=无 开始菜单(开始选项)

也可以返回值

ans=开始菜单() 在“开始”菜单中返回“开始”选项

要访问函数中的变量,可以这样做:

def fun():
    fun.x=1

fun()
print(fun.x)                   #will print 1

或者只使用global variable,您可以使用global在函数中访问和修改它

x=None

def fun():
    global x
    x=1

fun()
print(x)                       #will print 1

注意:我建议使用global而不是第一种方法。

if..else部分移到方法

def startmenu():#this is to call back here at any time
    startmenuoption = 1
    while startmenuoption == 1:
        startoption = raw_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!")

    if startoption in ["Check"]:
        print("Checking!")
    else:
        print("Okay!")
startmenu()

相关问题 更多 >