简体   繁体   中英

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.

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.

I don't see the keyword def in your code snippet, which would indicate the beginning of a function definition. Is the snippet taken from the body of a function?

Here is a working sample of return in a for loop:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM