即使未定义其参数,如何让函数继续运行

How to have a function continue even if its parameters are not defined

我正在制作一个游戏,用户可以在其中进行选择,我想创建一个功能来轻松地为我打印问题,但并非每个问题都有 5 个答案。我怎样才能让它只打印那些有参数的。我尝试了下面的方法,但它不起作用。

def sceneQuestion(question, Aone, Atwo, Athree, Afour, Afive):
    print(question)
    global choice
    choice="?"
    print(' ')
    print("  <a> "+Aone)
    print("  <b> "+Atwo)
    try:
      Athree
    except NameError:
      print(' ')
    else:
      print (' <c> '+Athree)
    try:
      Afour
    except NameError:
     print(' ')
    else:
      print (' <d> '+Afour)
    try:
     Afive
    except NameError:
     print(' ')
    else:
     print (' <e> '+Afive)
sceneQuestion('What do you want to do?', 'Eat food', 'Save George', 'Call George an idiot')

我该怎么做,谢谢。

有问题请评论

这是您使用可选参数的时候。在这种情况下,它应该是一系列参数。

def question(question, *answers):
    # answers is now a list of everything passed
    # to the function OTHER than the first argument
    print(question)
    for lett, ans in zip(string.ascii_lowercase, answers):
        print("  <{L}>  {ans}".format(L=lett, ans=ans))

为了完整起见,如果问题不更适合通过 *args,您可以按照以下方式解决问题,如 Adam 的回答:

def sceneQuestion(question, Aone, Atwo, Athree=None, Afour=None, Afive=None):
    print(question)
    global choice
    choice="?"
    print(' ')
    print("  <a> "+Aone)
    print("  <b> "+Atwo)
    if Athree is not None: print (' <c> '+Athree)
    if Afour is not None:  print (' <d> '+Afour)
    if Afive is not None:  print (' <e> '+Afive)

可以在函数签名中设置默认参数值,然后在您的代码中检查 None