python中可能存在也可能不存在的函数参数



所以我这里有一个示例函数:

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

我可以嵌套函数吗?

用可选参数定义函数,例如:

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

现在你可以用任意数量的参数来调用它,例如:

options(option2='Y')
#N Y

创建一个这样的类。类可以使函数调用更加干净。我建议做一些类似的事情:

`class Options:
def __init__ ():
self.option1 = None
self.option2 = None
# ect.
def choice4 (op1,op2,op3,op4):
# function 
# ect`

否则,你可以试试字典,或者按照其他人的建议,创建一个列表

最新更新