python NameError:名称"xxx"未定义 [英] python NameError: name 'xxx' is not defined

查看:331
本文介绍了python NameError:名称"xxx"未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

puzzle = [[' 1', ' 2', ' 3', ' 4'], [' 5', ' 6', ' 7', ' 8'],[ ' 9', '10', '11', '12'], ['13', '14', '15', ' X']]

def find_pos(alist, item):
    for i in alist:
        for j in range(4):
            if i[j] == item:
                row = alist.index(i)
                col = j

find_pos(puzzle,' X')

a = row
print(a)

我想我通过运行函数find_pos定义了名称row,如果没有,该如何解决以获取row

I think I defined the name row by running the function find_pos, if not, how to fix it to get row

请勿在find_pos函数

推荐答案

只需从函数中返回值:

puzzle = [[' 1', ' 2', ' 3', ' 4'], [' 5', ' 6', ' 7', ' 8'],[ ' 9', '10', '11', '12'], ['13', '14', '15', ' X']]

def find_pos(alist, item):
    for i in alist:
        for j in range(4):
            if i[j] == item:
                row = alist.index(i)
                col = j
                return row, col

row, col = find_pos(puzzle,' X')

print(row)

请注意,如果未找到该项目,它将返回None(因为默认情况下,不返回任何内容的每个函数都将返回None),在这种情况下,代码将引发错误.

Note that if the item isn't found, it will return None (because every function that doesn't return anything returns None by default), in which case the code will throw an error.

这篇关于python NameError:名称"xxx"未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆