Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 做出不完整的IF语句_Python_If Statement - Fatal编程技术网

Python 做出不完整的IF语句

Python 做出不完整的IF语句,python,if-statement,Python,If Statement,我正在制作一个小的地下城爬虫文本游戏,有一个特定的代码我想使用,但我不知道如何使用。我想创建一个IF语句,该语句有一个不完整的end语句 if cmd.lower() == "examine ...": 这三个点将是用户选择的任何内容。选项的数量太多,不可能每个选项都有那么多IF语句。有没有什么方法可以让我只把他们输入的检查部分用在IF语句中?您需要对输入字符串进行标记,然后根据命令(即第一个标记)分派结果 您可以探索如下解决方案: def examine(thing): print(

我正在制作一个小的地下城爬虫文本游戏,有一个特定的代码我想使用,但我不知道如何使用。我想创建一个IF语句,该语句有一个不完整的end语句

if cmd.lower() == "examine ...":

这三个点将是用户选择的任何内容。选项的数量太多,不可能每个选项都有那么多IF语句。有没有什么方法可以让我只把他们输入的检查部分用在IF语句中?

您需要对输入字符串进行标记,然后根据命令(即第一个标记)分派结果

您可以探索如下解决方案:

def examine(thing):
    print(f'It is a {thing}')

def attack(target):
    print(f'You strike {target}.  It seems offended.')

def tokenise_input(inp):
    command, *args = inp.split(' ')

    return (command, args)

def dispatch(command, *args):
    commands = {
        'examine': examine,
        'kill': attack,
        'attack': attack,
        ...,
    }

    return commands[command](*args)

command, args = tokenise_input(cmd)

dispatch(command, *args)
我相信您可以想象扩展命令字典以允许用户使用更多的命令,每个命令都指向自己的函数

上面的字符串插值语法f'…'在3.6中是新的,在早期版本中会导致语法错误。我建议您使用3.6,因为它非常棒,但如果您不能使用,请将其替换为:

def examine(thing):
    print('It is a {thing}'.format(thing=thing))

cmd.lower.startswithinspect,也许?哇,printf{thing}语法叫什么?以前从没见过!这是采用良好可扩展实践的一个很好的例子。f-sring被称为文本字符串插值,是自Python 3.6以来新增的:是的,它非常令人兴奋。我将更新答案,指出f-strings是新的,以及如何使用not-f-strings。如果输入不在字典中,我将如何这样说,跳过该命令并给出给定消息?我想不出我应该把它放在哪里,这样它才能有效地工作。我也许能做到,但非常混乱。在当前时刻,如果我键入字典中没有的内容,整个过程就会崩溃。