0

我在 python 中打印列表时遇到问题,因为每当我发出显示列表的命令时,它都不会显示该列表。以下是列表所在的整个函数引用的代码:

    #FUNCTIONS
def help():
    print("list of commands\n"
          + "help = Display of commands\n"
          + "list = list of all the Latin I vocabulary\n"
          + "Quit = exits the main program to the exit credits and then exits the app\n")
def userInstructions(userInput):
    if (userInput == "help" or "Help"):
        help()
    elif(userInput == "list" or "List"):
        list()


    return input("\nEnter your responce: ")


def list():
    a = ["salve" , "vale" , "et" , "est" , "in" , "sunt" , "non" , "insula" , "sed" , "oppidum"
                , "quoque" , "canis" , "coquus" , "filia" , "filius" , "hortus" , "mater" , "pater" , "servus" , "via" , "amicus" , "ancilla" , "cena" , "cibus"
                , "intro" , "saluto" , "porto" , "video" , "dominus" , "laetus" , "mercator" , "audio" , "dico" , "unus" , "duo" , "tres" , "quattuor" , "quinque"
                , "sex" , "septem" , "octo" , "novem" , "decem" , "ad" , "ecce" , "magnus" , "parvus" , "ambulo" , "iratus" , "quis" , "quid" , "cur" , "ubi" ,
                "sum" , "es" , "eheu" , "pecunia" , "ego" , "tu" , "habeo" , "respondeo" , "venio" , "rideo" , "quod" , "ex" , "voco" , "clamo" , "specto" , "taberna"
                , "laboro" , "clamor" , "femina" , "vir", "puer" , "puella" , "multus" , "urbs" , "agricola" , "curro" , "hodie" , "iuvenis" , "meus" , "senex" , "sto" ,
                "optimus" , "volo" , "fortis" , "emo" , "pulso" , "bonus" , "malus" , "festino" , "per" , "pugno" , "scribo" , "tuus" , "erat" , "paro" , "cum" , "facio" ,
                "heri" , "ingens" , "nihil" , "omnis" , "vendo" , "navis" , "prope" , "rogo" , "terreo" , "inquit" , "tamen" , "eum" , "eam" , "duco" , "saepe" , "interficio" ,
                "habito" , "silva" , "statim" , "totus" , "pessimus"]

    print("List:")
    print('\n'.join(map(str, a)))

下图显示了当我命令代码打印列表而不是打印列表时的结果,而是打印帮助面板: 命令结果

我的代码有什么问题,我该如何解决?

4

2 回答 2

3

userInput == "help" or "Help"被 Python 解释为(userInput == "help") or "Help",这将永远是正确的。而是尝试:

userInput == "help" or userInput == "Help"

或者

userInput in ["help","Help"]

或者

userInput.lower() == "help"

(同样对于userInput == "list" or "List")。

另外我不建议命名你的函数list(),它与内置的 python 函数冲突。

于 2019-11-22T03:56:24.533 回答
2

罪魁祸首是:

if (userInput == "help" or "Help"):

你需要:

if userInput in ('help', 'Help'):

或者:

if userInput == 'help' or userInput == 'Help':

'==' 的优先级大于 'or',因此您的 'if' 被视为:

if (userInput == 'help') or ('Help'):

因为“帮助”在逻辑上等同于“真”,所以您永远不会通过第一次if检查。

当您想要不区分大小写时,只需在检查之前转换为全部大写或小写。所以你也可以说:

if userInput.lower() == 'help':

有许多不同的方法可以做到这一点。有些人认为某些方式比其他方式好得多。但诀窍是让它发挥作用。

另外,作为旁注,您可以只说'\n'.join(a)没有mapand str,因为看起来列表中的所有条目都已经是字符串。如果您可能还有其他东西,那么mapstr很有帮助。

于 2019-11-22T03:58:06.390 回答