2017-09-22 60 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

相關問題