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