2017-02-11 85 views
-2

所以,我有一個例子功能在這裏:函數的參數,可能會或可能不存在

def options(option1,option2): 
    if option1 == 'y': 
     print("Yay") 
    else: 
     print("No") 

    if option2 == 'y': 
     print("Cool") 
    else: 
     print("Stop") 

然後,當我打電話的功能,我必須使用被列出的所有必需的參數。

userInput = input("Type Y or N: ") 
userInput2 = input("Type Y or N: ") 
options(userInput,userInput2) 

現在,這裏是我的問題:

我正在做一個基於文本的冒險遊戲,用戶可以選擇的選項1 - 4。我想有一個定義的方法,我將能夠調用無論提供多少選項。在一個場景中,我可能有3個選項可以給用戶。在另一個,我可能只有1.我怎麼能不必這樣做:

#if there's 4 options in the scene call this method: 
def options4(option1,option2,option3,option4): 
    blabla 

#if there's 3 options in the scene call this method: 
def options3(option1,option2,option3): 
    blabla 

#if there's 2 options in the scene call this method: 
def options2(option1,option2): 
    blabla 

#if there's 1 option in the scene call this method: 
def options1(option1): 
    blabla 

我可能嵌套功能?

+0

也許考慮做的選項清單,讓您可以有一個處理任何單一功能選項數量。 – PressingOnAlways

回答

0

定義可選參數的函數,例如:

def options(option1='N', option2='N'): 
    print(option1, option2) 

現在你可以用任何數量的參數調用它,例如:

options(option2='Y') 
#N Y 
0

創建一個類的這一點。一個類可以使函數調用更清潔。我建議做這樣的事情:

`class Options: 
    def __init__(): 
     self.option1 = None 
     self.option2 = None 
     # ect. 

    def choice4 (op1,op2,op3,op4): 
     # function 
    # ect` 

否則,你可以嘗試一本字典,或其他人則建議,創建一個列表

相關問題