Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.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 - Fatal编程技术网

python需要if函数的帮助

python需要if函数的帮助,python,Python,我想让这个函数去测试3个语句并返回相应的响应。这三种说法是正确的,它们的预期回应是 ''-要获得响应“空白, “你好”-回答为“单个单词”, “世界”-回答“另一个词” 问题是“world”也给出了“single word”而不是“single word reach”的响应。python有没有办法检测到之前的响应是“single word”,因此如果在第一个单词之后输入另一个单词,它会给出“single word reach”语句 def return_statement(statement):

我想让这个函数去测试3个语句并返回相应的响应。这三种说法是正确的,它们的预期回应是

''-要获得响应“空白,
“你好”-回答为“单个单词”,
“世界”-回答“另一个词”

问题是“world”也给出了“single word”而不是“single word reach”的响应。python有没有办法检测到之前的响应是“single word”,因此如果在第一个单词之后输入另一个单词,它会给出“single word reach”语句

def return_statement(statement):
    if statement == (''):
        response = "blank space"
        return response
    if ' ' not in statement
        response = "single word"
        return response
    if ' ' not in statement and response == "single word":
        response = 'single word again'
        return response

在函数
return\u语句中,
response
是一个局部变量。这意味着在函数执行结束并返回后,
response
不再存在-我们说它的作用域就是它所在的函数。当您离开变量的作用域时,它将消失

以下是您可以采取的一些方法:

1) 使
return\u语句的调用方保持从它周围返回的
response
,调用时除了
statement
之外还传入
response
。这使
return\u语句的调用方负责

2) 将
response
设为全局变量,因此其范围是不确定的


3) 使
response
成为类的实例变量。只要继续使用同一个类实例,它的
response
值将因此在调用之间保持不变。

要存储以前响应的状态,可以向函数添加属性。我只是在函数中添加属性,而不会对你的逻辑

def return_statement(statement):
    // Check if has attribute, otherwise init
    if not hasattr(return_statement, "prev"):
         return_statement.prev = ''
    if statement == (''):
        response = "blank space"
        // Store answer before returning
        return_statement.prev = response
        return response
    // Fix logic
    if ' ' not in statement:
        if "single word" in return_statement.prev:
            response = "single word again"
        else:
            response = "single word"
            // Store answer
            return_statement.prev = response
        return response

除了在下面的回答中指出的事情之外……我认为你缺少了一个“:“对于第二个if语句……你描述问题的方式似乎与你的要求相矛盾。“世界”应该返回“另一个单词”还是“单一世界”?