python NameError: name 'xxx' is not defined

走远了吗. 提交于 2019-11-27 09:07:34

问题


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)

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

Do not put any print in the find_pos function


回答1:


Just return the values from the function:

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)

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.



来源:https://stackoverflow.com/questions/35920320/python-nameerror-name-xxx-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!