如何改进我的输入命令

时间:2017-08-14 18:13:54

标签: python if-statement input while-loop

我正在寻找能够改进,简化甚至整理输入命令的任何建议。我看到重复不是一个好习惯。

while(char.health > 0):
    print("_____________________________________")
    line = input("\n>").lower().split()
    if len(line) < 1:
        print ("{} doesn't understand the command?".format(char.name))
    elif line[0] == "go":
        commands.movement()
    elif line[0] == "quit":
        commands.quit()
    elif line[0] == "rest":
        commands.rest()
    else:
        print ("{} doesn't understand the command?".format(char.name))

我看到有些人使用这样的字典:

    cmd = {'go' : commands.movement()} 

当我这样做时,似乎在没有被调用的情况下运行def!

解决。
我已经找到了解决方案。

cmd = { "go" : (commands.movement)}

这是我的新命令dict。我意识到commands.movement()正在调用def。

while (char.health > 0):
    print("_________________________________________")
    line = input(">").lower().split()
    if len(line) < 1:
        print ("Invalid command!")
    elif line[0] in cmd:
        cmd[line[0]]()     #this now calls the def instead
    else:
        print("Invalid command!")

0 个答案:

没有答案