Home > Net >  how to resolve outside fuction error for return in pythons
how to resolve outside fuction error for return in pythons

Time:08-15

Was trying to run code ended up with return outside

For row in rows:
If list1.index(0)== list2.index(0):
return new-list.append(row[0])
Elif list1.index(1)== list2.index(1):
return new-list.append(row[1])
Elif list1.index(2)== list2.index(2):
return new-list.append(row[2])
Elif list1.index(3)== list2.index(3):
return new-list.append(row[3])

getting return outside function error

CodePudding user response:

Python does not use braces to create code blocks like C or Java, instead it uses tabs/spaces to create what is known as code blocks if code is not indented then that part is not inside a code block. For example

x = 10
if x == 10:
   print("X is 10") # This is inside if statement
print("Not if") # but this is not inside if statement so it will execute regardless of if statement.

So you need to indent your return statements to fix those errors. Also F and E of for and elif should be in small letters and variables cannot contain -(dash) in their names.

for row in rows:
    if list1.index(0) == list2.index(0):
        return newList.append(row[0])
    elif list1.index(1) == list2.index(1):
        return newList.append(row[1])
    elif list1.index(2) == list2.index(2):
        return newList.append(row[2])
    elif list1.index(3) == list2.index(3):
        return newList.append(row[3])

CodePudding user response:

The keyword return can only be used inside a function definition.

def helloworld():
    return 'Hello World!'
print(helloworld()) # Hello World!

What you want might be something like this:

for row in rows: 
    if list1.index(0) == list2.index(0):
        newList.append(row[0])
    elif list1.index(1) == list2.index(1):
        newList.append(row[1])
    elif list1.index(2) == list2.index(2):
        newList.append(row[2])
    elif list1.index(3) == list2.index(3):
        newList.append(row[3])

Also, keywords like if, elif can't be capitalized (Only True, False, and None are capitalized). And an indent is needed after every colon. And python variables can't contain -.

  • Related