2017-09-22 59 views
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!") 

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

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

+0

要做到这一点的方法是通过传递和返回函数中的值 –

+0

函数调用下的代码的目的是什么?它看起来像在函数本身的功能 – Mangohero1

+0

'return startoption'中执行的功能一样。然后,在调用你的函数时,就像'startoption = startmenu()'一样。这些是你所拥有的最低(不是最好的)改变。 – CristiFati

回答

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

这是完美的作品。 – johnnu

0

对于访问内部函数中的变量,你可以做这样的:

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,而不是第一个方法。

+0

我想删除第一部分:) – CristiFati

+0

只是建议。我知道它有点不常用。 –

0

有几个解决方案。你可以通过这个作为参数传入你的函数,你调用STARTMENU(之前定义它)是这样的:

startoption =无 STARTMENU(startoption)

你也可以返回值

ANS = STARTMENU() 在STARTMENU回报startoption

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

'startoption = str'? – CristiFati

相关问题