You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Python中return语句的'return outside function'错误

解决'return outside function'错误及代码问题

错误根源与修复步骤

  1. return语句的合法范围:return只能在函数内部使用,你的代码直接在全局循环中写return,Python无法识别其作用域,必须将逻辑封装到函数中。
  2. 修正关键字大小写:Python是大小写敏感语言,关键字for、if、elif必须小写,原代码中的For、If、Elif会被视为无效变量名,引发语法错误。
  3. 修正非法变量名:new-list中的减号会被解析为减法运算符,变量名需改为new_list(仅允许使用字母、数字、下划线)。
  4. 纠正append方法的使用:list.append()是原地修改列表的方法,返回值为None,不能直接return new_list.append(...),需先执行append操作,再返回列表本身。

修正后的代码示例(找到第一个匹配即返回)

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

遍历所有行的版本(收集所有符合条件的元素)

如果需求是遍历所有rows并收集所有匹配项,而非找到第一个就终止,可将return移到循环外:

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

内容的提问来源于stack exchange,提问作者greeg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 13:09:27