-2
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

timgeb
  • 76,762
  • 20
  • 123
  • 145
Ren Yuan
  • 49
  • 1
  • 1
  • 4
  • 1
    The variables created within a function do not end up in global scope after the function is called. – g.d.d.c Mar 10 '16 at 15:14
  • Python scope/block is defined by indentation... – Ian Mar 10 '16 at 15:15
  • Hello and welcome on stackoverflow. Please keep all code associated with the question, so there's no mess trying to read it. – zmo Mar 10 '16 at 15:16

1 Answers1

4

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.

L3viathan
  • 26,748
  • 2
  • 58
  • 81
  • One comment: If I'm reading this right, the `return row, col` statement should be at the same indentation level as the `for`. Otherwise it will do a return the first time through the lists where `i[j] == item`. – Deacon Mar 10 '16 at 17:15
  • @DougR. I believe that is the indended effect: To find the first instance of where `i[j] == item`. – L3viathan Mar 10 '16 at 17:33
  • My apologies. I missed that from the explanation and the sample code. – Deacon Mar 10 '16 at 17:39