[英]Python: return outside function error
for x in non_neutral.collect():
tweet = str(x[2])
sid = x[1]
status = x[0]
text = word_tokenize(tweet)
text1 = list(text)
tweet = x[2].split()
pronoun = intersect(second_pronoun,tweet)
perojective = intersect(less_offensive,tweet)
if pronoun:
pronoun_index = tweet.index(pronoun[0])
pero_index = tweet.index(perojective[0])
if pero_index <= pronoun_index+3:
status = 1
return Row(status=status,tid=sid,tweet = str(tweet))
else:
status = 0
return Row(status=status,tid=sid,tweet = str(tweet))
For this particular snippet of code I am constantly getting this error and I don't understand why 对于此特定代码段,我一直在收到此错误,但我不明白为什么
File "<ipython-input-5-0484b7e6e4fa>", line 15
return Row(status=status,tid=sid,tweet = str(tweet))
SyntaxError: 'return' outside function
I have tried writing the code again but still getting the same error. 我尝试再次编写代码,但仍然遇到相同的错误。
your program doesn't actually contain a function. 您的程序实际上不包含函数。 Return statements must be contained within a function, you haven't defined any in this case.
Return语句必须包含在一个函数中,在这种情况下,您尚未定义任何返回语句。
Try something more like the following (note that this doesn't include all of your code it is just an example): 尝试类似以下的内容(请注意,这并不包括您的所有代码,仅是示例):
def Foo():
#Here is where you put all of your code
#Since it is now in a function a value can be returned from it
if pronoun:
pronoun_index = tweet.index(pronoun[0])
pero_index = tweet.index(perojective[0])
if pero_index <= pronoun_index+3:
status = 1
return Row(status=status,tid=sid,tweet = str(tweet))
else:
status = 0
return Row(status=status,tid=sid,tweet = str(tweet))
Foo()
So long as you put your code in a function it will work. 只要将代码放在函数中,它就可以工作。 The syntax for a basic function definition in python is:
def Foo(Bar):
Where Foo is the name of the function and Bar is any parameters you may need, each separated by a comma. python中基本函数定义的语法为:
def Foo(Bar):
其中Foo是函数的名称,而Bar是您可能需要的任何参数,每个参数都用逗号分隔。
I don't see the keyword def
in your code snippet, which would indicate the beginning of a function definition. 我在您的代码段中没有看到关键字
def
,这表明函数定义的开始。 Is the snippet taken from the body of a function? 代码片段是否取自函数的主体?
Here is a working sample of return in a for loop: 这是一个for循环中的return的工作示例:
from random import shuffle
def loop_return():
values = [0,1]
shuffle(values)
for i in values:
if i == 0:
return 'Zero first.'
if i == 1:
return 'One first.'
You don't actually have a function, so you can't return anything. 您实际上没有函数,因此您无法返回任何内容。 You could fix it by making the code a procedure.
您可以通过使代码成为一个过程来解决它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.