Search code examples
pythonfor-loopif-statementreturn

how to resolve outside fuction error for return in pythons


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


Solution

  • 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 -.