2017-02-11 72 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` 

否则,你可以尝试一本字典,或其他人则建议,创建一个列表

相关问题