-1

This code doesn't work.

error says:

UnboundLocalError: local variable 'on' referenced before assignment

arr = []
for i in range(4):
    arr.append([0 for t in range(4)])

on=1

num_r = 0
def go_r(d):
    for i in range(d):
        arr[num_r][i+num_r] = on
        on +=1
    return arr

print(go_r(4))

but this code(↓) works.

arr = []
for i in range(4):
    arr.append([0 for t in range(4)])

on=1

num_r = 0
def go_r(d):
    for i in range(d):
        arr[num_r][i+num_r] = on
    return arr

print(go_r(4))

Difference between two codes is the upper code includes "on +=1"

I want my code to print [[1, 2, 3, 4], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]].

So I insert "on +=1" in upper code.

What should I do? I don't know what's the problem on the upper code.

  • In your first code fragment you are modifying *on* but in the second you're just reading it. In your first fragment add *global on* inside the *go_r()* function – DarkKnight Jan 06 '22 at 08:24
  • [This](https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html#more-about-scope-crossing-boundaries) should explain it, with examples that are almost identical to your case. – Amadan Jan 06 '22 at 08:26

1 Answers1

0
def go_r(d):
    for i in range(d):
        arr[num_r][i+num_r] = on
        on +=1
    return arr

In the above case, on variable is a local variable in go_r function.

Add global on in the function to use global variable on.

def go_r(d):
    global on
    for i in range(d):
        arr[num_r][i+num_r] = on
        on +=1
    return arr
Ice Griffin
  • 430
  • 1
  • 10