即使未定义参数,如何继续使用函数

时间:2015-06-03 18:59:04

标签: python function parameters

我正在制作一个游戏,其中有用户可以选择的选项,我想创建一个功能来轻松打印问题,但不是每个问题都有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')

我将如何做到这一点,谢谢。

如果您有任何问题,请发表评论

2 个答案:

答案 0 :(得分:3)

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

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))

答案 1 :(得分:1)

为了完整性,如果问题不太适合传递*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