使用定义循环外的变量,在一个定义内部定义

时间:2017-09-22 18:03:17

标签: python python-3.x

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

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

我知道删除定义循环似乎是一个简单的选项,但这正是我试图避免的,因为我需要它。

4 个答案:

答案 0 :(得分:0)

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

def fun():
    fun.x=1

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

或者只使用global variable,您可以使用global在您的函数中访问和修改。{/ p>

x=None

def fun():
    global x
    x=1

fun()
print(x)                       #will print 1

注意:我建议使用 global 代替第一种方法。

答案 1 :(得分:0)

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()

答案 2 :(得分:0)

这有几个解决方案。您可以将此参数作为参数传递给函数,并在调用startmenu()之前定义它:

startoption =无 STARTMENU(startoption)

你也可以返回值

ans = startmenu() 在startmenu返回startoption

答案 3 :(得分:0)

我的解决方案是在调用函数时返回值:

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

startoption = startmenu()
if startoption in ["Check"]:
    print("Checking!")
else:
    print("Okay!")
相关问题